diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bb0255..817724d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,33 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +## [0.9.0-ptb.6] - 2026-11-28 + +### Added +- Framework support for Qbox, QBCore, ESX Legacy, ox_core and ND_Core. `config/framework.json` maps framework jobs to departments and agencies, and job grades to ranks. With a framework, the character's job decides who can go on duty and at what rank, players show by their character's name, and duty stays in step with Qbox and QBCore. Framework characters get FivePRS records, so citations, warrants, licenses and the MDT work with them, their owned vehicles are found by plate, and citation fines come out of the character's bank. Spawning and clothing are left to the framework. FivePRS still runs standalone when no framework is found +- `xpEnabled` in `config/settings.json` turns XP off, so ranks are only set by admins. The terminal hides XP when it's off +- Patrol car radar with front and rear antennas that read same-direction or oncoming traffic, separate front (`J`) and rear (`U`) locks, closing and away indicators, an error reading while turning or airborne, a doppler tone and beeps, and a digital display. The operator menu (`F9`) sets each antenna, a fast limit with optional auto-lock, volumes, and the display's size and position, and remembers them. A plate reader checks the vehicles in front and behind against records and flags stolen vehicles, wanted owners, suspended licenses and unregistered plates, shows plates in their in-game style, can be locked (`O`), and alerts on plates in each officer's watch list. Officers riding as passengers see the driver's radar and can lock it. A handheld lidar gun measures speed and distance on foot, with its own reticle when aiming; `radar.lidarWeapon` sets the weapon it uses. Every radar lock and lidar reading is kept for 30 days as a speed clock in **Records › Speed**, where an officer can run the plate or start a citation pre-filled with the clock. Settings are under `radar` in `config/settings.json` +- **As I am** in the Duty app starts your shift with your current look and no vehicle. It's the default, and the Duty app remembers the start you used last +- Rename the police, EMS and fire departments and give them your own icons in the new `config/departments//department.json`, which FivePRS creates on start. The names show everywhere players see a department +- Agencies can have their own `icon`, shown in the Duty app and Dispatch in place of the department's +- **Book suspect** in the station menu at the duty point ends custody once you've brought your suspect in. Press `H` on foot beside your vehicle to take a suspect back out first. Resources can listen for `FivePRS:Local:SuspectBooked` +- Callout helpers `WaitForArrivalAsync`, `WaitUntilWitnessedAsync` and `CanSee`, with the standard `SpawnDistance`, `SightDistance` and `CloseDistance` + +### Changed +- `jurisdictions.json` is checked one entry at a time. A territory or agency with a mistake is skipped with a console warning that says what's wrong, and the rest of the file loads, instead of the whole file falling back to the defaults. Agencies can be added with any id and name +- Department names in config files are no longer case-sensitive, and a department's display name works too, so `"department": "carabinieri"` is accepted once police is renamed to Carabinieri +- A framework job mapped to an agency no longer needs a `department`; it comes from the agency +- `fprs_setdept` accepts a department's display name as well as `police`, `ems` or `fire` +- Callouts set up their scene when you're about 150 m away, and start the action (a fight, a getaway or a pursuit) once you can see it or are within 15 m + +### Fixed +- Shoplifting no longer ends as soon as it's accepted when the store is more than 300 m away. The suspect waits near the store and runs once you find them. Thanks to phoenixpinpoint for the first fix (#11) +- Vehicle Pursuit no longer starts the chase before you're near. You're sent to where the stolen car was last seen; it drives normally until you're close, then flees +- Domestic Disturbance no longer ends early because the people at the scene spawned far away and fell through the map, and the fight no longer finishes before you arrive. Verbal arguments stay verbal +- Arrested suspects no longer get stuck in a loop between the cuffed pose and following you. They walk with you while cuffed +- Pulled-over vehicles no longer drive off in a loop to a point on another road before stopping. They pull to the side of their own road, or stop where they are +- Starting a shift at a **Station** now gives you your uniform, loadout and a vehicle parked outside, as the Duty app says. Before, it only teleported you there + ## [0.9.0-ptb.5] - 2026-10-14 ### Added @@ -148,8 +175,10 @@ The first public test build. - Only Mission Row has armory, locker room and garage points - Back up your database before updating between test builds -[Unreleased]: https://github.com/FivePRS/core/compare/v0.9.0-ptb.3...HEAD -[0.9.0-ptb.3]: https://github.com/FivePRS/core/compare/v0.9.0-ptb.3...v0.9.0-ptb.4 +[Unreleased]: https://github.com/FivePRS/core/compare/v0.9.0-ptb.6...HEAD +[0.9.0-ptb.6]: https://github.com/FivePRS/core/compare/v0.9.0-ptb.5...v0.9.0-ptb.6 +[0.9.0-ptb.5]: https://github.com/FivePRS/core/compare/v0.9.0-ptb.4...v0.9.0-ptb.5 +[0.9.0-ptb.4]: https://github.com/FivePRS/core/compare/v0.9.0-ptb.3...v0.9.0-ptb.4 [0.9.0-ptb.3]: https://github.com/FivePRS/core/compare/v0.9.0-ptb.2...v0.9.0-ptb.3 [0.9.0-ptb.2]: https://github.com/FivePRS/core/compare/v0.9.0-ptb.1...v0.9.0-ptb.2 [0.9.0-ptb.1]: https://github.com/FivePRS/core/releases/tag/v0.9.0-ptb.1 diff --git a/FivePRS.Client/Agency/DepartmentAgency.cs b/FivePRS.Client/Agency/DepartmentAgency.cs index 211fcb5..0d3b10b 100644 --- a/FivePRS.Client/Agency/DepartmentAgency.cs +++ b/FivePRS.Client/Agency/DepartmentAgency.cs @@ -42,7 +42,9 @@ public override async Task OnDuty(PlayerData player) _dispatcher.Start(); var mode = StationService.TakePendingStart(out var station); - var message = ShouldEquip(mode) + var message = mode == DutyStartMode.Current + ? $"You're on duty as you are. Collect your {EquipmentNoun} at a station when you need them." + : ShouldEquip(mode) ? await EquipAsync(player, mode, station) : await ReportToStationAsync(mode, station); @@ -70,7 +72,7 @@ public override async Task OnCalloutReceived(CalloutData callout) { DutyEquipmentMode.Always => true, DutyEquipmentMode.Station => false, - _ => mode == DutyStartMode.Here, + _ => mode == DutyStartMode.Here || mode == DutyStartMode.Teleport, }; private async Task EquipAsync(PlayerData player, DutyStartMode mode, StationDef? station) @@ -163,7 +165,7 @@ private void OnCalloutEnded(CalloutBase callout, CalloutResult result) if (result == CalloutResult.Completed) Notify("~g~CALLOUT COMPLETE~w~"); else if (result == CalloutResult.Failed) - Notify("~r~CALLOUT FAILED~w~ | No XP awarded."); + Notify(ClientBrain.LocalPlayerData.UsesXp ? "~r~CALLOUT FAILED~w~ | No XP awarded." : "~r~CALLOUT FAILED"); Log.Debug($"Callout '{callout.Data.Name}' ended: {result}."); } diff --git a/FivePRS.Client/App/AdminPanel.cs b/FivePRS.Client/App/AdminPanel.cs index 99bee26..369702b 100644 --- a/FivePRS.Client/App/AdminPanel.cs +++ b/FivePRS.Client/App/AdminPanel.cs @@ -44,13 +44,15 @@ public static void Act(IDictionary data) => return new { State = _state, + XpEnabled = ClientBrain.LocalPlayerData.UsesXp, + Framework = ClientBrain.LocalPlayerData.Framework, Ranks = ConfigManager.Departments.ToDictionary( - d => d.ToString(), + d => ((int)d).ToString(), d => Enumerable.Range(1, ConfigManager.RanksFor(d).Count).Select(rank => ConfigManager.RanksFor(d).NameFor(rank)).ToList()), Departments = Enum.GetValues(typeof(Department)) .Cast() .Where(d => d != Department.None) - .Select(d => new { Id = (int)d, Name = d.ToString() }) + .Select(d => new { Id = (int)d, Name = ConfigManager.DisplayName(d) }) .ToList(), }; } diff --git a/FivePRS.Client/App/AppClient.cs b/FivePRS.Client/App/AppClient.cs index a2cc444..a385812 100644 --- a/FivePRS.Client/App/AppClient.cs +++ b/FivePRS.Client/App/AppClient.cs @@ -44,6 +44,7 @@ public AppClient() EventHandlers[EventNames.ClientLookupResult] += new Action(OnLookupResult); EventHandlers[EventNames.ClientLookupError] += new Action(OnLookupError); EventHandlers[EventNames.ClientReports] += new Action(OnReports); + EventHandlers[EventNames.ClientSpeedClocks] += new Action(OnSpeedClocks); EventHandlers[EventNames.ClientEmergencyStatus] += new Action(OnEmergencyStatus); EventHandlers[EventNames.ClientEmergencyError] += new Action(OnEmergencyError); EventHandlers[EventNames.ClientAdminState] += new Action(OnAdminState); @@ -160,6 +161,21 @@ private void OnLookupResult(string json) Refresh(); } + private void OnSpeedClocks(string json) + { + try + { + RecordsPanel.SetClocks(json); + } + catch (Exception ex) + { + Log.Error("Could not read speed clocks", ex); + return; + } + + Refresh(); + } + private void OnReports(string json) { try @@ -383,7 +399,7 @@ private static object BuildState(string? requestedApp) return new { Nameplate = ConfigManager.Settings.Branding.Nameplate, - Icons = ConfigManager.Settings.Branding.Departments, + Icons = ConfigManager.Icons(), Terminal = TerminalPanel.BuildView(), Apps = TerminalApps.BuildList(), AppView = TerminalApps.BuildOpenView(), diff --git a/FivePRS.Client/App/CivilianPanel.cs b/FivePRS.Client/App/CivilianPanel.cs index e1ffab3..d4e6fb3 100644 --- a/FivePRS.Client/App/CivilianPanel.cs +++ b/FivePRS.Client/App/CivilianPanel.cs @@ -166,7 +166,7 @@ public static object BuildView() Genders = CivilianRules.Genders, MaxNameLength = CivilianRules.MaxNameLength, CurrentVehicle = vehicle, - Icons = ConfigManager.Settings.Branding.Departments, + Icons = ConfigManager.Icons(), StateInfo = ConfigManager.Licenses.State, Mugshot = _mugshot, }; diff --git a/FivePRS.Client/App/DispatchPanel.cs b/FivePRS.Client/App/DispatchPanel.cs index 5017855..66eb38e 100644 --- a/FivePRS.Client/App/DispatchPanel.cs +++ b/FivePRS.Client/App/DispatchPanel.cs @@ -86,7 +86,7 @@ public static void RequestBackup(IDictionary data) return new { self.Callsign, - Agency = ConfigManager.Territories.FindAgency(self.Agency)?.Name ?? self.Department.ToString(), + Agency = ConfigManager.Territories.FindAgency(self.Agency)?.Name ?? ConfigManager.DisplayName(self.Department), Status = self.Status.ToString(), }; } @@ -120,8 +120,10 @@ public static void RequestBackup(IDictionary data) self.ServerId, self.Callsign, self.Name, - Department = self.Department.ToString(), - Agency = map.FindAgency(self.Agency)?.Name ?? self.Department.ToString(), + Department = ConfigManager.DisplayName(self.Department), + DepartmentKey = ConfigManager.ConfigName(self.Department), + AgencyId = self.Agency, + Agency = map.FindAgency(self.Agency)?.Name ?? ConfigManager.DisplayName(self.Department), Status = self.Status.ToString(), self.CallId, Territory = map.FindTerritory(self.Territory)?.Name, @@ -132,7 +134,7 @@ public static void RequestBackup(IDictionary data) call.Id, call.Name, Code = (int)call.Priority, - Department = call.Department.ToString(), + Department = ConfigManager.DisplayName(call.Department), Territory = map.FindTerritory(call.Territory)?.Name, HasLocation = call.X != 0f || call.Y != 0f, DistanceM = call.X != 0f || call.Y != 0f @@ -155,13 +157,13 @@ public static void RequestBackup(IDictionary data) unit.ServerId, unit.Callsign, unit.Name, - Department = unit.Department.ToString(), - Agency = map.FindAgency(unit.Agency)?.Name ?? unit.Department.ToString(), + Department = ConfigManager.DisplayName(unit.Department), + Agency = map.FindAgency(unit.Agency)?.Name ?? ConfigManager.DisplayName(unit.Department), Status = unit.Status.ToString(), unit.CallId, Territory = map.FindTerritory(unit.Territory)?.Name, }), - icons = ConfigManager.Settings.Branding.Departments, + icons = ConfigManager.Icons(), }; } } diff --git a/FivePRS.Client/App/DutyPanel.cs b/FivePRS.Client/App/DutyPanel.cs index b69aa69..df5ebaa 100644 --- a/FivePRS.Client/App/DutyPanel.cs +++ b/FivePRS.Client/App/DutyPanel.cs @@ -68,9 +68,10 @@ public static void SetOnDuty(bool isOnDuty) private static string? SetStart(IDictionary data, Department department, string agencyId) { var rawMode = NuiData.GetString(data, "start"); - if (!Enum.TryParse(rawMode, true, out var mode) || mode == DutyStartMode.Here) + if (!Enum.TryParse(rawMode, true, out var mode)) mode = DutyStartMode.Current; + if (mode == DutyStartMode.Current || mode == DutyStartMode.Here) { - StationService.SetPendingStart(DutyStartMode.Here, null); + StationService.SetPendingStart(mode, null); return null; } @@ -99,8 +100,9 @@ public static object BuildView() .Select(d => new { Id = (int)d, - Name = d.ToString(), - Agencies = map.AgenciesFor(d).Select(a => new { a.Id, a.Name, a.CallsignPrefix }).ToList(), + Name = ConfigManager.DisplayName(d), + Key = ConfigManager.ConfigName(d), + Agencies = map.AgenciesFor(d).Select(a => new { a.Id, a.Name, a.CallsignPrefix, HasIcon = !string.IsNullOrWhiteSpace(a.Icon) }).ToList(), Stations = ConfigManager.Stations.For(d, null) .Select(s => new { s.Id, s.Name, s.Agencies, Distance = (int)StationService.DistanceTo(s) }) .OrderBy(s => s.Distance) @@ -117,19 +119,22 @@ public static object BuildView() RankCount = profile.Ladder().Count, Stats = new { Calls = profile.CallsCompleted, profile.Arrests, Hours = profile.DutySeconds / 3600 }, profile.XP, + profile.UsesXp, XpToNext = profile.Ladder().XpToNext(profile.Rank), profile.IsOnDuty, DepartmentId = (int)profile.Department, - Department = profile.Department.ToString(), + Department = ConfigManager.DisplayName(profile.Department), + DepartmentKey = ConfigManager.ConfigName(profile.Department), AgencyId = profile.Agency, profile.Callsign, CallsignMaxLength = Callsign.MaxLength, - Icons = ConfigManager.Settings.Branding.Departments, + Icons = ConfigManager.Icons(), Departments = departments, Unit = unit is null ? null : new { unit.Callsign, - Agency = map.FindAgency(unit.Agency)?.Name ?? unit.Department.ToString(), + Agency = map.FindAgency(unit.Agency)?.Name ?? ConfigManager.DisplayName(unit.Department), + AgencyId = unit.Agency, }, }; } diff --git a/FivePRS.Client/App/RecordsPanel.cs b/FivePRS.Client/App/RecordsPanel.cs index 8bc0ec6..84e08b5 100644 --- a/FivePRS.Client/App/RecordsPanel.cs +++ b/FivePRS.Client/App/RecordsPanel.cs @@ -6,6 +6,7 @@ using FivePRS.Core.Config; using FivePRS.Core.Events; using FivePRS.Core.Models; +using FivePRS.Core.Police; using Newtonsoft.Json; namespace FivePRS.Client.App @@ -22,6 +23,7 @@ internal static class RecordsPanel private static string? _query; private static LookupRecord? _record; private static ReportsView? _reports; + private static List? _clocks; public static int DraftCount => _reports?.Drafts.Count ?? 0; @@ -42,6 +44,10 @@ public static void SetReports(string json) public static void RequestReports() => ClientEvents.TriggerServer(EventNames.ServerReportsRequest); + public static void SetClocks(string json) => _clocks = JsonConvert.DeserializeObject>(json) ?? new List(); + + public static void RequestClocks() => ClientEvents.TriggerServer(EventNames.ServerSpeedClocksRequest); + public static void SaveReport(IDictionary data) { if (NuiData.TryGetInt(data, "reportId", out var id)) @@ -194,6 +200,7 @@ public static void FlagVehicle(IDictionary data) { Medical = !Police, Reports = Police ? null : _reports, + Clocks = Police ? _clocks : null, MaxNarrative = ReportRules.MaxNarrativeLength, AutoFileMinutes = ReportRules.AutoFileMinutes, Stop = Police ? StreetIdentity.CurrentStop?.Invoke() : null, diff --git a/FivePRS.Client/Arrest/ArrestManager.cs b/FivePRS.Client/Arrest/ArrestManager.cs index 5b4cde8..2573b9d 100644 --- a/FivePRS.Client/Arrest/ArrestManager.cs +++ b/FivePRS.Client/Arrest/ArrestManager.cs @@ -21,6 +21,7 @@ public static class ArrestManager public const float CuffRangeM = 2.5f; public const float EscortRangeM = 5.0f; + public const float BookRangeM = 5.0f; private const string CuffAnimDict = "mp_arresting"; private const string CuffAnimClip = "idle"; @@ -174,12 +175,87 @@ public static async Task EscortToVehicleAsync(Vehicle vehicle) State = ArrestState.Escorted; ClientBrain.ShowNotification("~g~Suspect secured in vehicle."); + ClientBrain.ShowHelp($"Drive to a station. On foot beside the vehicle, press {Binds.Escort} to take the suspect out.", 6_000); ClientEvents.TriggerLocal(EventNames.LocalSuspectEscorted, suspect.Handle, vehicle.Handle); Log.Debug($"Suspect placed in vehicle {vehicle.Handle}."); return true; } + public static async Task TakeOutOfVehicleAsync() + { + if (!IsEscorted || CuffedPed is null || !CuffedPed.Exists()) return false; + + var suspect = CuffedPed; + var vehicle = suspect.CurrentVehicle; + if (vehicle is null || !vehicle.Exists()) + { + State = ArrestState.Cuffed; + StartFollowTask(suspect); + return true; + } + + var distance = Vector3.Distance(Game.PlayerPed.Position, vehicle.Position); + if (distance > EscortRangeM) + { + ClientBrain.ShowNotification($"~r~Too far from the vehicle~w~ ({distance:F0}m). Get within ~w~{EscortRangeM}m~r~ first."); + return false; + } + + suspect.Task.ClearAll(); + API.TaskLeaveVehicle(suspect.Handle, vehicle.Handle, 0); + for (var i = 0; i < 30 && suspect.Exists() && suspect.IsInVehicle(); i++) + await BaseScript.Delay(100); + + if (suspect.Exists() && suspect.IsInVehicle()) + API.TaskLeaveVehicle(suspect.Handle, vehicle.Handle, 16); + + await BaseScript.Delay(300); + if (!suspect.Exists()) return false; + + State = ArrestState.Cuffed; + await ApplyCuffedAnimationAsync(suspect); + StartFollowTask(suspect); + + ClientBrain.ShowNotification("~g~Suspect out of the vehicle."); + return true; + } + + public static string? BookingProblem() + { + if (CuffedPed is null || !CuffedPed.Exists()) return "No suspect in custody"; + if (IsEscorted) return $"Take the suspect out of the vehicle ({Binds.Escort})"; + if (Vector3.Distance(Game.PlayerPed.Position, CuffedPed.Position) > BookRangeM) return "Bring the suspect closer"; + return null; + } + + public static async Task BookAsync(string location) + { + var problem = BookingProblem(); + if (problem is not null) + { + ClientBrain.ShowNotification($"~r~{problem}."); + return false; + } + + var suspect = CuffedPed!; + var handle = suspect.Handle; + + CuffedPed = null; + State = ArrestState.None; + _registeredSuspects.Remove(handle); + + API.NetworkFadeOutEntity(handle, false, true); + await BaseScript.Delay(1_000); + if (suspect.Exists()) suspect.Delete(); + + ClientBrain.ShowNotification($"~g~Suspect booked~w~ at {location}."); + ClientEvents.TriggerLocal(EventNames.LocalSuspectBooked, handle, location); + + Log.Debug($"Suspect {handle} booked at {location}."); + return true; + } + private static Ped? FindNearestRegisteredSuspect() { var playerPos = Game.PlayerPed.Position; @@ -226,8 +302,8 @@ await suspect.Task.PlayAnimation( blendInSpeed: 8f, blendOutSpeed: -8f, duration: -1, - flags: AnimationFlags.Loop | AnimationFlags.StayInEndFrame, - playbackRate: 0f); + flags: AnimationFlags.Loop | AnimationFlags.UpperBodyOnly | AnimationFlags.AllowRotation, + playbackRate: 1f); } internal static void ClearCuffedState() diff --git a/FivePRS.Client/Arrest/ArrestTick.cs b/FivePRS.Client/Arrest/ArrestTick.cs index ed5e640..8a829d9 100644 --- a/FivePRS.Client/Arrest/ArrestTick.cs +++ b/FivePRS.Client/Arrest/ArrestTick.cs @@ -10,7 +10,9 @@ public class ArrestTick : BaseScript private const int FollowRecheckIntervalMs = 2_000; - private const float StandStillThresholdM = 0.5f; + private const uint FollowTaskHash = 0x304AE42E; + + private const int TaskFinished = 7; private int _animTickCounter = 0; private int _followTickCounter = 0; @@ -65,17 +67,8 @@ private async Task OnTickAsync() { _followTickCounter = 0; - var distToPlayer = Vector3.Distance( - suspect.Position, Game.PlayerPed.Position); - - if (distToPlayer <= StandStillThresholdM) - { - suspect.Task.StandStill(-1); - } - else - { + if (API.GetScriptTaskStatus(suspect.Handle, FollowTaskHash) == TaskFinished) ArrestManager.StartFollowTask(suspect); - } } await Delay(50); diff --git a/FivePRS.Client/Callouts/CalloutBase.cs b/FivePRS.Client/Callouts/CalloutBase.cs index 72ff487..d3f5ab6 100644 --- a/FivePRS.Client/Callouts/CalloutBase.cs +++ b/FivePRS.Client/Callouts/CalloutBase.cs @@ -103,6 +103,41 @@ protected static Vector3 PickLocation(IReadOnlyList locations, Random r return pool[rng.Next(pool.Count)]; } + public const float SpawnDistance = 150f; + + public const float SightDistance = 40f; + + public const float CloseDistance = 15f; + + protected static async Task WaitForArrivalAsync(Vector3 position, float distance, CancellationToken ct) + { + while (Vector3.Distance(Game.PlayerPed.Position, position) > distance) + await Timing.WaitAsync(500, ct); + } + + protected static bool CanSee(Entity? target, float range = SightDistance) + { + if (target is null || !target.Exists()) return false; + + var distance = Vector3.Distance(Game.PlayerPed.Position, target.Position); + return distance <= range && API.HasEntityClearLosToEntity(Game.PlayerPed.Handle, target.Handle, 17); + } + + protected static async Task WaitUntilWitnessedAsync(Entity target, CancellationToken ct, + float sightRange = SightDistance, float closeRange = CloseDistance) + { + while (true) + { + if (!target.Exists()) return false; + if (target is Ped ped && ped.IsDead) return false; + + var distance = Vector3.Distance(Game.PlayerPed.Position, target.Position); + if (distance <= closeRange || CanSee(target, sightRange)) return true; + + await Timing.WaitAsync(250, ct); + } + } + protected async Task WaitForArrestAsync(Ped suspect, CancellationToken ct, string? prompt = null) { const int PollMs = 250; diff --git a/FivePRS.Client/ClientBrain.cs b/FivePRS.Client/ClientBrain.cs index bc540b7..b0d2bc5 100644 --- a/FivePRS.Client/ClientBrain.cs +++ b/FivePRS.Client/ClientBrain.cs @@ -62,6 +62,12 @@ public ClientBrain() }), false); API.RegisterCommand(KeyCommands.Escort, new Action, string>(async (_, __, ___) => { + if (ArrestManager.IsEscorted && !Game.PlayerPed.IsInVehicle()) + { + await ArrestManager.TakeOutOfVehicleAsync(); + return; + } + var vehicle = Game.PlayerPed.CurrentVehicle; if (vehicle == null || !vehicle.Exists()) { @@ -79,10 +85,10 @@ public ClientBrain() } var d = LocalPlayerData; - var agency = ConfigManager.Territories.FindAgency(d.Agency)?.Name ?? d.Department.ToString(); + var agency = ConfigManager.Territories.FindAgency(d.Agency)?.Name ?? ConfigManager.DisplayName(d.Department); ShowNotification( $"~b~{d.Name}~w~ | {agency} | {d.RankName()}~n~~g~" + - (d.Ladder().IsTop(d.Rank) ? "Top rank" : $"XP: {d.XP} / {d.Ladder().XpToNext(d.Rank)}")); + (!d.UsesXp ? ConfigManager.DisplayName(d.Department) : d.Ladder().IsTop(d.Rank) ? "Top rank" : $"XP: {d.XP} / {d.Ladder().XpToNext(d.Rank)}")); }), false); API.RegisterCommand("er_help", new Action, string>((_, __, ___) => { diff --git a/FivePRS.Client/HudAnchor.cs b/FivePRS.Client/HudAnchor.cs new file mode 100644 index 0000000..2f9967a --- /dev/null +++ b/FivePRS.Client/HudAnchor.cs @@ -0,0 +1,27 @@ +using System; +using CitizenFX.Core.Native; + +namespace FivePRS.Client +{ + public static class HudAnchor + { + private const float SafeZoneMargin = 0.05f; + private const float MinimapHeightRatio = 5.674f; + + public static object Minimap() + { + var aspect = API.GetAspectRatio(false); + var inset = SafeZoneMargin * Math.Abs(API.GetSafeZoneSize() - 1f) * 10f; + var bottom = 1f - inset; + + return new + { + left = inset, + top = bottom - 1f / MinimapHeightRatio, + bottom, + width = 1f / (4f * aspect), + visible = !API.IsRadarHidden(), + }; + } + } +} diff --git a/FivePRS.Client/PublicState.cs b/FivePRS.Client/PublicState.cs index 7a65133..509a340 100644 --- a/FivePRS.Client/PublicState.cs +++ b/FivePRS.Client/PublicState.cs @@ -19,7 +19,8 @@ public static IDictionary Build() { ["name"] = player.Name, ["onDuty"] = player.IsOnDuty, - ["department"] = player.Department.ToString(), + ["department"] = player.Department.ToString(), + ["departmentName"] = ConfigManager.DisplayName(player.Department), ["rank"] = player.Rank, ["rankName"] = player.RankName(), ["prefs"] = new Dictionary @@ -32,7 +33,7 @@ public static IDictionary Build() if (!player.IsOnDuty) return state; - state["agency"] = map.FindAgency(player.Agency)?.Name ?? player.Department.ToString(); + state["agency"] = map.FindAgency(player.Agency)?.Name ?? ConfigManager.DisplayName(player.Department); state["callsign"] = player.Callsign; var unit = DispatchClient.LocalUnit; diff --git a/FivePRS.Client/Stations/StationMenu.cs b/FivePRS.Client/Stations/StationMenu.cs index 4f2a853..24c2ddb 100644 --- a/FivePRS.Client/Stations/StationMenu.cs +++ b/FivePRS.Client/Stations/StationMenu.cs @@ -4,6 +4,7 @@ using CitizenFX.Core; using FivePRS.Client.Agency; using FivePRS.Client.App; +using FivePRS.Client.Arrest; using FivePRS.Client.Appearance; using FivePRS.Client.Loadout; using FivePRS.Client.Menu; @@ -47,16 +48,8 @@ public static void Open(StationDef station, StationPoint point) }, IconFor(station.Department)); } - private static string IconFor(Department department) - { - var icons = ConfigManager.Settings.Branding.Departments; - return department switch - { - Department.EMS => icons.Ems, - Department.Fire => icons.Fire, - _ => icons.Police, - }; - } + private static string IconFor(Department department) => + ConfigManager.IconFor(department == Department.None ? Department.Police : department); private static MenuPage PageFor(StationDef station, StationPoint point) => point switch { @@ -73,6 +66,22 @@ private static MenuPage Root(StationDef station) foreach (var point in GearPoints.Where(p => !StationService.HasOwnPoint(station, p))) page.Items.Add(new MenuItem { Label = point.ToString(), Submenu = () => PageFor(station, point) }); + if (ArrestManager.HasCustody) + { + var problem = ArrestManager.BookingProblem(); + page.Items.Add(new MenuItem + { + Label = "Book suspect", + Detail = problem, + Disabled = problem is not null, + Select = async () => + { + CompactMenu.Close(); + await ArrestManager.BookAsync(station.Name); + }, + }); + } + page.Items.Add(new MenuItem { Label = "Duty menu", diff --git a/FivePRS.Client/Stations/StationService.cs b/FivePRS.Client/Stations/StationService.cs index 2f0337e..60f6e6a 100644 --- a/FivePRS.Client/Stations/StationService.cs +++ b/FivePRS.Client/Stations/StationService.cs @@ -11,6 +11,7 @@ namespace FivePRS.Client.Stations { public enum DutyStartMode { + Current, Here, Teleport, Drive @@ -41,10 +42,11 @@ public static DutyStartMode TakePendingStart(out StationDef? station) var mode = _pendingMode; station = ConfigManager.Stations.Find(_pendingStationId); - _pendingMode = DutyStartMode.Here; + _pendingMode = DutyStartMode.Current; _pendingStationId = null; - return station is null ? DutyStartMode.Here : mode; + if (mode == DutyStartMode.Current || mode == DutyStartMode.Here) return mode; + return station is null ? DutyStartMode.Current : mode; } public static Vector3 PositionOf(StationDef station) => diff --git a/FivePRS.Client/Terminal/Apps/EmergencyApp.cs b/FivePRS.Client/Terminal/Apps/EmergencyApp.cs index aabaaba..cec8185 100644 --- a/FivePRS.Client/Terminal/Apps/EmergencyApp.cs +++ b/FivePRS.Client/Terminal/Apps/EmergencyApp.cs @@ -45,11 +45,11 @@ public class EmergencyApp : TerminalApp Departments = Enum.GetValues(typeof(Department)) .Cast() .Where(d => d != Department.None && BaseAgency.IsDepartmentLoaded(d)) - .Select(d => new { Id = (int)d, Name = d.ToString() }) + .Select(d => new { Id = (int)d, Name = ConfigManager.DisplayName(d), Key = ConfigManager.ConfigName(d) }) .ToList(), Status = _status, MaxLength = CivilianRules.MaxEmergencyLength, - Icons = ConfigManager.Settings.Branding.Departments, + Icons = ConfigManager.Icons(), Location = HomePanel.CurrentLocation(), }; diff --git a/FivePRS.Client/Terminal/Apps/RecordsApp.cs b/FivePRS.Client/Terminal/Apps/RecordsApp.cs index f84015b..a5333ba 100644 --- a/FivePRS.Client/Terminal/Apps/RecordsApp.cs +++ b/FivePRS.Client/Terminal/Apps/RecordsApp.cs @@ -57,6 +57,10 @@ public override void OnAction(string action, IDictionary data) RecordsPanel.RequestReports(); break; + case "clocks": + RecordsPanel.RequestClocks(); + break; + case "reportSave": RecordsPanel.SaveReport(data); break; diff --git a/FivePRS.Client/Terminal/SettingsApp.cs b/FivePRS.Client/Terminal/SettingsApp.cs index 9c8c0b7..d50aeb6 100644 --- a/FivePRS.Client/Terminal/SettingsApp.cs +++ b/FivePRS.Client/Terminal/SettingsApp.cs @@ -20,6 +20,12 @@ public class SettingsApp : TerminalApp new[] { KeyCommands.EndCall, "End your call" }, new[] { KeyCommands.Backup, "Request backup" }, new[] { KeyCommands.TrafficStop, "Traffic stop" }, + new[] { KeyCommands.Radar, "Toggle radar" }, + new[] { KeyCommands.RadarLock, "Lock front radar" }, + new[] { KeyCommands.RadarRearLock, "Lock rear radar" }, + new[] { KeyCommands.RadarRemote, "Radar operator menu" }, + new[] { KeyCommands.PlateLock, "Lock plate reader" }, + new[] { KeyCommands.Lidar, "Toggle lidar gun" }, new[] { KeyCommands.Cuff, "Cuff" }, new[] { KeyCommands.Uncuff, "Uncuff" }, new[] { KeyCommands.Escort, "Escort to vehicle" }, diff --git a/FivePRS.Core/Civilian/CivilianModels.cs b/FivePRS.Core/Civilian/CivilianModels.cs index 5ca8fc9..e0ce3fe 100644 --- a/FivePRS.Core/Civilian/CivilianModels.cs +++ b/FivePRS.Core/Civilian/CivilianModels.cs @@ -28,6 +28,7 @@ public sealed class CharacterInfo public DateTime CreatedAt { get; set; } public DateTime LastUsedAt { get; set; } public string? Photo { get; set; } + public string? ExternalId { get; set; } public string FullName => $"{FirstName} {LastName}"; } @@ -59,6 +60,7 @@ public sealed class CivilianState public List Records { get; set; } = new(); public int MaxCharacters { get; set; } public int MaxVehicles { get; set; } + public string? ManagedBy { get; set; } } public sealed class LicenseCard diff --git a/FivePRS.Core/Civilian/RecordModels.cs b/FivePRS.Core/Civilian/RecordModels.cs index 144a75c..c20a93c 100644 --- a/FivePRS.Core/Civilian/RecordModels.cs +++ b/FivePRS.Core/Civilian/RecordModels.cs @@ -13,6 +13,13 @@ public enum RecordType Medical = 4, } + public enum FineStatus + { + None = 0, + Unpaid = 1, + Paid = 2, + } + public sealed class RecordInfo { public int Id { get; set; } @@ -25,6 +32,7 @@ public sealed class RecordInfo public DateTime CreatedAt { get; set; } public bool Active { get; set; } public string? Resolution { get; set; } + public FineStatus FineStatus { get; set; } } public sealed class CharacterSummary diff --git a/FivePRS.Core/Config/ConfigFiles.cs b/FivePRS.Core/Config/ConfigFiles.cs index acb432c..527c265 100644 --- a/FivePRS.Core/Config/ConfigFiles.cs +++ b/FivePRS.Core/Config/ConfigFiles.cs @@ -10,7 +10,9 @@ public static class ConfigFiles public const string Stations = "config/world/stations.json"; public const string Licenses = "config/civilian/licenses.json"; public const string Citations = "config/civilian/citations.json"; + public const string Framework = "config/framework.json"; + public const string Info = "department"; public const string Ranks = "ranks"; public const string Loadouts = "loadouts"; public const string Vehicles = "vehicles"; diff --git a/FivePRS.Core/Config/ConfigManager.cs b/FivePRS.Core/Config/ConfigManager.cs index ab46849..e5caf82 100644 --- a/FivePRS.Core/Config/ConfigManager.cs +++ b/FivePRS.Core/Config/ConfigManager.cs @@ -5,6 +5,7 @@ using FivePRS.Core.Logging; using FivePRS.Core.Models; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; namespace FivePRS.Core.Config { @@ -17,6 +18,7 @@ public static class ConfigManager public static LicensesConfig Licenses { get; private set; } = new(); public static StationsConfig Stations { get; private set; } = new(); public static CitationsConfig Citations { get; private set; } = new(); + public static FrameworkConfig Framework { get; private set; } = new(); public static TerritoryMap Territories { get; private set; } = new(new JurisdictionConfig()); public static readonly Department[] Departments = { Department.Police, Department.Fire, Department.EMS }; @@ -24,9 +26,74 @@ public static class ConfigManager private static readonly Dictionary DepartmentLoadouts = new(); private static readonly Dictionary DepartmentVehicles = new(); private static readonly Dictionary DepartmentRanks = new(); + private static readonly Dictionary DepartmentInfos = new(); public static string ConfigName(Department department) => department.ToString().ToLowerInvariant(); + public static string DefaultName(Department department) => department.ToString(); + + public static string DisplayName(Department department) => + DepartmentInfos.TryGetValue(department, out var info) && !string.IsNullOrWhiteSpace(info.Name) + ? info.Name.Trim() + : DefaultName(department); + + public static DepartmentInfo DefaultInfo(Department department) => new() { Name = DefaultName(department) }; + + public static string IconFor(Department department) + { + if (DepartmentInfos.TryGetValue(department, out var info) && !string.IsNullOrWhiteSpace(info.Icon)) + return info.Icon.Trim(); + + var branding = Settings.Branding.Departments; + return department switch + { + Department.Police => branding.Police, + Department.EMS => branding.Ems, + Department.Fire => branding.Fire, + _ => branding.Civilian, + }; + } + + public static string AgencyIconKey(string agencyId) => "agency:" + agencyId.ToLowerInvariant(); + + public static Dictionary Icons() + { + var icons = new Dictionary + { + ["civilian"] = Settings.Branding.Departments.Civilian, + }; + + foreach (var department in Departments) + icons[ConfigName(department)] = IconFor(department); + + foreach (var agency in Jurisdictions.Agencies) + { + if (!string.IsNullOrWhiteSpace(agency.Icon) && !string.IsNullOrWhiteSpace(agency.Id)) + icons[AgencyIconKey(agency.Id)] = agency.Icon.Trim(); + } + + return icons; + } + + public static bool TryParseDepartment(string? text, out Department department) + { + department = Department.None; + if (text is null || string.IsNullOrWhiteSpace(text)) return false; + + var value = text.Trim(); + foreach (var candidate in Departments) + { + if (string.Equals(ConfigName(candidate), value, StringComparison.OrdinalIgnoreCase) || + string.Equals(DisplayName(candidate), value, StringComparison.OrdinalIgnoreCase)) + { + department = candidate; + return true; + } + } + + return false; + } + public static DepartmentLoadoutsConfig LoadoutsFor(Department department) => DepartmentLoadouts.TryGetValue(department, out var config) ? config : DefaultLoadouts(department); @@ -57,6 +124,7 @@ public static void LoadAll(Func readFile) LoadSettings(Read(ConfigFiles.Settings)); foreach (var department in Departments) { + LoadDepartmentInfo(department, Read(ConfigFiles.Department(department, ConfigFiles.Info))); LoadDepartment(department, Read(ConfigFiles.Department(department, ConfigFiles.Ranks)), Read(ConfigFiles.Department(department, ConfigFiles.Loadouts)), @@ -67,6 +135,7 @@ public static void LoadAll(Func readFile) LoadLicenses(Read(ConfigFiles.Licenses)); LoadStations(Read(ConfigFiles.Stations)); LoadCitations(Read(ConfigFiles.Citations)); + LoadFramework(Read(ConfigFiles.Framework)); } public static void LoadDepartment(Department department, string? ranksJson, string? loadoutsJson, string? vehiclesJson) @@ -85,6 +154,25 @@ public static void LoadDepartment(Department department, string? ranksJson, stri DepartmentRanks[department] = new RankLadder(ranks); } + public static void LoadDepartmentInfo(Department department, string? json) + { + var info = DefaultInfo(department); + if (json is not null && !string.IsNullOrWhiteSpace(json)) + { + try + { + JsonConvert.PopulateObject(json, info); + } + catch (Exception ex) + { + Log.Error($"{ConfigName(department)}/department.json has an error, using the default name and icon", ex); + info = DefaultInfo(department); + } + } + + DepartmentInfos[department] = info; + } + public static DepartmentRanksConfig DefaultRanks(Department department) => department switch { Department.Fire => DepartmentRanksConfig.Fire(), @@ -133,12 +221,139 @@ private static T Populate(string? json, string fileName, Func defaults) wh public static void LoadStations(string? json) => Stations = Load(json, "stations.json", Stations); public static void LoadCitations(string? json) => Citations = Load(json, "citations.json", Citations); + public static void LoadFramework(string? json) + { + if (json is null || string.IsNullOrWhiteSpace(json)) + { + Framework = new FrameworkConfig(); + return; + } + + try + { + Framework = JsonConvert.DeserializeObject(json, new JsonSerializerSettings + { + ObjectCreationHandling = ObjectCreationHandling.Replace, + }) ?? new FrameworkConfig(); + } + catch (Exception ex) + { + Log.Error("framework.json has an error, using defaults", ex); + Framework = new FrameworkConfig(); + } + } + public static void LoadJurisdictions(string? json) { - Jurisdictions = Load(json, "jurisdictions.json", Jurisdictions); + Jurisdictions = ParseJurisdictions(json); Territories = new TerritoryMap(Jurisdictions); } + public static JurisdictionConfig ParseJurisdictions(string? json) + { + const string File = "jurisdictions.json"; + var config = new JurisdictionConfig(); + + if (json is null || string.IsNullOrWhiteSpace(json)) + { + Log.Warn($"{File} is missing or empty, using defaults."); + return config; + } + + JObject root; + try + { + root = JObject.Parse(json); + } + catch (Exception ex) + { + Log.Error($"{File} is not valid JSON, using defaults", ex); + return config; + } + + if (root["territories"] is JArray territories) + { + config.Territories = new List(); + var index = 0; + foreach (var item in territories) + { + index++; + var label = EntryLabel(item, "territory", index); + try + { + var territory = item.ToObject(); + if (territory is null || string.IsNullOrWhiteSpace(territory.Id)) + Log.Warn($"{File}: skipped {label} because it has no id."); + else if (territory.Polygon.Count(point => point.Length >= 2) < 3) + Log.Warn($"{File}: skipped {label} because its polygon needs at least 3 points."); + else if (config.Territories.Any(t => SameId(t.Id, territory.Id))) + Log.Warn($"{File}: skipped {label} because another territory already uses that id."); + else + config.Territories.Add(territory); + } + catch (Exception ex) + { + Log.Warn($"{File}: skipped {label}. {ex.Message}"); + } + } + } + + if (root["agencies"] is JArray agencies) + { + config.Agencies = new List(); + var index = 0; + foreach (var item in agencies) + { + index++; + var label = EntryLabel(item, "agency", index); + try + { + var agency = item.ToObject(); + if (agency is null || string.IsNullOrWhiteSpace(agency.Id)) + Log.Warn($"{File}: skipped {label} because it has no id."); + else if (agency.Department == Department.None) + Log.Warn($"{File}: skipped {label} because it has no department. Use police, ems or fire."); + else if (config.Agencies.Any(a => SameId(a.Id, agency.Id))) + Log.Warn($"{File}: skipped {label} because another agency already uses that id."); + else + config.Agencies.Add(agency); + } + catch (Exception ex) + { + Log.Warn($"{File}: skipped {label}. {ex.Message}"); + } + } + } + + foreach (var agency in config.Agencies) + { + if (string.IsNullOrWhiteSpace(agency.Name)) agency.Name = agency.Id; + + foreach (var territory in agency.Territories) + { + if (!config.Territories.Any(t => SameId(t.Id, territory))) + Log.Warn($"{File}: agency \"{agency.Id}\" lists territory \"{territory}\", which is not defined in territories."); + } + } + + foreach (var department in Departments) + { + if (!config.Agencies.Any(a => a.Department == department)) + Log.Warn($"{File}: no agency uses the {ConfigName(department)} department, so {DisplayName(department)} units have no agency to pick."); + } + + Log.Debug($"{File} loaded: {config.Territories.Count} territories, {config.Agencies.Count} agencies."); + return config; + } + + private static string EntryLabel(JToken item, string kind, int index) + { + var id = (item as JObject)?["id"]?.ToString(); + return string.IsNullOrWhiteSpace(id) ? $"{kind} #{index}" : $"{kind} \"{id}\""; + } + + private static bool SameId(string a, string b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + private static T Load(string? json, string fileName, T fallback) where T : class { if (json is null || string.IsNullOrWhiteSpace(json)) diff --git a/FivePRS.Core/Config/DepartmentConverter.cs b/FivePRS.Core/Config/DepartmentConverter.cs new file mode 100644 index 0000000..e90f8b4 --- /dev/null +++ b/FivePRS.Core/Config/DepartmentConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Linq; +using FivePRS.Core.Models; +using Newtonsoft.Json; + +namespace FivePRS.Core.Config +{ + public sealed class DepartmentConverter : JsonConverter + { + public override bool CanConvert(Type objectType) => objectType == typeof(Department); + + public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Integer) + { + var number = Convert.ToInt32(reader.Value); + if (Enum.IsDefined(typeof(Department), number)) return (Department)number; + throw new JsonSerializationException($"{number} is not a department. Use police, ems or fire."); + } + + if (reader.TokenType == JsonToken.Null) return Department.None; + + var text = Convert.ToString(reader.Value)?.Trim() ?? string.Empty; + if (ConfigManager.TryParseDepartment(text, out var department)) return department; + + throw new JsonSerializationException( + $"\"{text}\" is not a department. Use police, ems or fire. To show another name, set it in config/departments//department.json."); + } + + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) => + writer.WriteValue(value is Department department ? ConfigManager.ConfigName(department) : null); + } +} diff --git a/FivePRS.Core/Config/DepartmentInfo.cs b/FivePRS.Core/Config/DepartmentInfo.cs new file mode 100644 index 0000000..d6263c7 --- /dev/null +++ b/FivePRS.Core/Config/DepartmentInfo.cs @@ -0,0 +1,13 @@ +using Newtonsoft.Json; + +namespace FivePRS.Core.Config +{ + public sealed class DepartmentInfo + { + [JsonProperty("name")] + public string Name { get; set; } = string.Empty; + + [JsonProperty("icon")] + public string Icon { get; set; } = string.Empty; + } +} diff --git a/FivePRS.Core/Config/FrameworkConfig.cs b/FivePRS.Core/Config/FrameworkConfig.cs new file mode 100644 index 0000000..6bf20d6 --- /dev/null +++ b/FivePRS.Core/Config/FrameworkConfig.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using FivePRS.Core.Models; +using Newtonsoft.Json; + +namespace FivePRS.Core.Config +{ + public sealed class FrameworkJob + { + [JsonConverter(typeof(DepartmentConverter))] + public Department Department { get; set; } + + public string? Agency { get; set; } + + public Dictionary? Ranks { get; set; } + } + + public sealed class FrameworkFines + { + public bool Collect { get; set; } = true; + public string Account { get; set; } = "bank"; + } + + public sealed class FrameworkJobMatch + { + public string Job { get; set; } = string.Empty; + public Department Department { get; set; } + public string? Agency { get; set; } + public int Rank { get; set; } + } + + public sealed class FrameworkConfig + { + public const string Auto = "auto"; + public const string Standalone = "standalone"; + + public static readonly string[] Supported = { "qbox", "qbcore", "esx", "ox", "nd" }; + + public string Framework { get; set; } = Auto; + + public FrameworkFines Fines { get; set; } = new(); + + public Dictionary Jobs { get; set; } = new(StringComparer.OrdinalIgnoreCase) + { + ["police"] = new FrameworkJob { Department = Department.Police, Agency = "lspd" }, + ["lspd"] = new FrameworkJob { Department = Department.Police, Agency = "lspd" }, + ["sheriff"] = new FrameworkJob { Department = Department.Police, Agency = "bcso" }, + ["bcso"] = new FrameworkJob { Department = Department.Police, Agency = "bcso" }, + ["ambulance"] = new FrameworkJob { Department = Department.EMS, Agency = "sams" }, + ["ems"] = new FrameworkJob { Department = Department.EMS, Agency = "sams" }, + ["fire"] = new FrameworkJob { Department = Department.Fire, Agency = "lsfd" }, + ["lsfd"] = new FrameworkJob { Department = Department.Fire, Agency = "lsfd" }, + }; + + public string Preferred => (Framework ?? Auto).Trim().ToLowerInvariant(); + + public FrameworkJobMatch? Resolve(string? job, int grade, Func rankCount) + { + if (string.IsNullOrWhiteSpace(job) || !TryFindJob(job!, out var name, out var mapping)) return null; + + var department = mapping.Department; + if (department == Department.None && !string.IsNullOrWhiteSpace(mapping.Agency)) + department = ConfigManager.Territories.FindAgency(mapping.Agency)?.Department ?? Department.None; + if (department == Department.None) return null; + + var count = Math.Max(1, rankCount(department)); + var rank = mapping.Ranks is not null && mapping.Ranks.TryGetValue(grade.ToString(CultureInfo.InvariantCulture), out var mapped) + ? mapped + : grade + 1; + + return new FrameworkJobMatch + { + Job = name, + Department = department, + Agency = string.IsNullOrWhiteSpace(mapping.Agency) ? null : mapping.Agency, + Rank = Math.Min(Math.Max(rank, 1), count), + }; + } + + private bool TryFindJob(string job, out string name, out FrameworkJob mapping) + { + foreach (var entry in Jobs) + { + if (!string.Equals(entry.Key, job.Trim(), StringComparison.OrdinalIgnoreCase) || entry.Value is null) continue; + name = entry.Key; + mapping = entry.Value; + return true; + } + + name = string.Empty; + mapping = null!; + return false; + } + } +} diff --git a/FivePRS.Core/Config/JurisdictionConfig.cs b/FivePRS.Core/Config/JurisdictionConfig.cs index 11046e4..154064d 100644 --- a/FivePRS.Core/Config/JurisdictionConfig.cs +++ b/FivePRS.Core/Config/JurisdictionConfig.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using FivePRS.Core.Models; using Newtonsoft.Json; -using Newtonsoft.Json.Converters; namespace FivePRS.Core.Config { @@ -26,7 +25,7 @@ public sealed class AgencyDef public string Name { get; set; } = string.Empty; [JsonProperty("department")] - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(DepartmentConverter))] public Department Department { get; set; } [JsonProperty("callsignPrefix")] @@ -34,6 +33,9 @@ public sealed class AgencyDef [JsonProperty("territories", ObjectCreationHandling = ObjectCreationHandling.Replace)] public List Territories { get; set; } = new(); + + [JsonProperty("icon")] + public string Icon { get; set; } = string.Empty; } public sealed class JurisdictionConfig diff --git a/FivePRS.Core/Config/RadarSettings.cs b/FivePRS.Core/Config/RadarSettings.cs new file mode 100644 index 0000000..8a424b0 --- /dev/null +++ b/FivePRS.Core/Config/RadarSettings.cs @@ -0,0 +1,43 @@ +using Newtonsoft.Json; + +namespace FivePRS.Core.Config +{ + public sealed class RadarSettings + { + [JsonProperty("enabled")] + public bool Enabled { get; set; } = true; + + [JsonProperty("units")] + public string Units { get; set; } = "mph"; + + [JsonProperty("range")] + public float Range { get; set; } = 150f; + + [JsonProperty("speedAlert")] + public int SpeedAlert { get; set; } + + [JsonProperty("plateReader")] + public bool PlateReader { get; set; } = true; + + [JsonProperty("plateReaderRange")] + public float PlateReaderRange { get; set; } = 35f; + + [JsonProperty("lidar")] + public bool Lidar { get; set; } = true; + + [JsonProperty("lidarRange")] + public float LidarRange { get; set; } = 300f; + + [JsonProperty("lidarWeapon")] + public string LidarWeapon { get; set; } = DefaultLidarWeapon; + + public const string DefaultLidarWeapon = "WEAPON_FLAREGUN"; + + [JsonIgnore] + public bool Metric => string.Equals(Units, "kmh", System.StringComparison.OrdinalIgnoreCase) || + string.Equals(Units, "km/h", System.StringComparison.OrdinalIgnoreCase); + + public int ToDisplaySpeed(float metresPerSecond) => + (int)System.Math.Round(metresPerSecond * (Metric ? 3.6f : 2.23694f)); + } +} diff --git a/FivePRS.Core/Config/RateLimitSettings.cs b/FivePRS.Core/Config/RateLimitSettings.cs index 372c555..4b98aa3 100644 --- a/FivePRS.Core/Config/RateLimitSettings.cs +++ b/FivePRS.Core/Config/RateLimitSettings.cs @@ -32,6 +32,15 @@ public sealed class RateLimitSettings [JsonProperty("lookups")] public RateLimit Lookups { get; set; } = new(20, 10); + [JsonProperty("plateReads")] + public RateLimit PlateReads { get; set; } = new(30, 10); + + [JsonProperty("radarControls")] + public RateLimit RadarControls { get; set; } = new(20, 10); + + [JsonProperty("speedClocks")] + public RateLimit SpeedClocks { get; set; } = new(15, 10); + [JsonProperty("records")] public RateLimit Records { get; set; } = new(10, 10); diff --git a/FivePRS.Core/Config/ResourceSettings.cs b/FivePRS.Core/Config/ResourceSettings.cs index ad28bdf..9ac0eb5 100644 --- a/FivePRS.Core/Config/ResourceSettings.cs +++ b/FivePRS.Core/Config/ResourceSettings.cs @@ -42,6 +42,9 @@ public sealed class ResourceSettings [JsonProperty("maxFine")] public int MaxFine { get; set; } = 10000; + [JsonProperty("xpEnabled")] + public bool XpEnabled { get; set; } = true; + [JsonProperty("emergencyCallCooldownSeconds")] public int EmergencyCallCooldownSeconds { get; set; } = 60; @@ -70,6 +73,9 @@ public sealed class ResourceSettings [JsonProperty("backup")] public BackupSettings Backup { get; set; } = new(); + [JsonProperty("radar")] + public RadarSettings Radar { get; set; } = new(); + [JsonProperty("terminal")] public TerminalSettings Terminal { get; set; } = new(); diff --git a/FivePRS.Core/Events/EventNames.cs b/FivePRS.Core/Events/EventNames.cs index 215fe83..56b21fe 100644 --- a/FivePRS.Core/Events/EventNames.cs +++ b/FivePRS.Core/Events/EventNames.cs @@ -17,6 +17,9 @@ public static class EventNames public const string ClientLookupError = "FivePRS:Client:LookupError"; public const string ClientStopResult = "FivePRS:Client:StopResult"; public const string ClientReports = "FivePRS:Client:Reports"; + public const string ClientPlateRead = "FivePRS:Client:PlateRead"; + public const string ClientRadarControl = "FivePRS:Client:RadarControl"; + public const string ClientSpeedClocks = "FivePRS:Client:SpeedClocks"; public const string ClientPlayerDowned = "FivePRS:Client:PlayerDowned"; public const string ClientDownedPlayers = "FivePRS:Client:DownedPlayers"; public const string ClientRevived = "FivePRS:Client:Revived"; @@ -74,6 +77,10 @@ public static class EventNames public const string ServerStopPlate = "FivePRS:Server:StopPlate"; public const string ServerRunPlate = "FivePRS:Server:RunPlate"; public const string ServerRunPerson = "FivePRS:Server:RunPerson"; + public const string ServerPlateRead = "FivePRS:Server:PlateRead"; + public const string ServerRadarControl = "FivePRS:Server:RadarControl"; + public const string ServerSpeedClock = "FivePRS:Server:SpeedClock"; + public const string ServerSpeedClocksRequest = "FivePRS:Server:SpeedClocksRequest"; public const string ServerReportDraft = "FivePRS:Server:ReportDraft"; public const string ServerReportsRequest = "FivePRS:Server:ReportsRequest"; public const string ServerReportSave = "FivePRS:Server:ReportSave"; @@ -91,11 +98,15 @@ public static class EventNames public const string LocalHttpResponse = "FivePRS:Local:HttpResponse"; public const string LocalDbRequest = "FivePRS:Local:DbRequest"; public const string LocalDbResponse = "FivePRS:Local:DbResponse"; + public const string LocalFrameworkRequest = "FivePRS:Local:FrameworkRequest"; + public const string LocalFrameworkResponse = "FivePRS:Local:FrameworkResponse"; + public const string LocalFrameworkChanged = "FivePRS:Local:FrameworkChanged"; public const string PublicAppAction = "fiveprs:appAction"; public const string LocalCalloutReceived = "FivePRS:Local:CalloutReceived"; public const string LocalSuspectCuffed = "FivePRS:Local:SuspectCuffed"; public const string LocalSuspectUncuffed = "FivePRS:Local:SuspectUncuffed"; public const string LocalSuspectEscorted = "FivePRS:Local:SuspectEscorted"; + public const string LocalSuspectBooked = "FivePRS:Local:SuspectBooked"; } } diff --git a/FivePRS.Core/Models/PlayerData.cs b/FivePRS.Core/Models/PlayerData.cs index 1e38d6e..71c39ab 100644 --- a/FivePRS.Core/Models/PlayerData.cs +++ b/FivePRS.Core/Models/PlayerData.cs @@ -16,6 +16,8 @@ public class PlayerData public int Arrests { get; set; } public int DutySeconds { get; set; } public DateTime? ShiftStartedAt { get; set; } + public bool UsesXp { get; set; } = true; + public string? Framework { get; set; } public DateTime LastSeen { get; set; } = DateTime.UtcNow; } } diff --git a/FivePRS.Core/Police/PlateFlags.cs b/FivePRS.Core/Police/PlateFlags.cs new file mode 100644 index 0000000..0b64bbe --- /dev/null +++ b/FivePRS.Core/Police/PlateFlags.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using FivePRS.Core.Civilian; + +namespace FivePRS.Core.Police +{ + public static class PlateFlag + { + public const string Stolen = "stolen"; + public const string Warrant = "warrant"; + public const string Unregistered = "unregistered"; + public const string Suspended = "suspended"; + } + + public sealed class PlateCheck + { + public string Plate { get; set; } = string.Empty; + public string? Model { get; set; } + public string? Owner { get; set; } + public List Flags { get; set; } = new(); + } + + public static class PlateFlags + { + public static PlateCheck FromRecord(string plate, VehicleInfo vehicle, LookupRecord? owner) + { + var check = new PlateCheck { Plate = plate, Model = vehicle.Model, Owner = owner is null ? null : $"{owner.Character.FirstName} {owner.Character.LastName}" }; + if (vehicle.Status == VehicleStatus.Stolen) check.Flags.Add(PlateFlag.Stolen); + if (owner is null) return check; + + if (owner.Character.HasActiveWarrant) check.Flags.Add(PlateFlag.Warrant); + foreach (var license in owner.Licenses) + { + if (license.Type == StreetProfiles.DriverLicenseType && (license.Status == LicenseStatus.Suspended || license.Status == LicenseStatus.Revoked)) + check.Flags.Add(PlateFlag.Suspended); + } + return check; + } + + public static PlateCheck FromProfile(string plate) + { + var vehicle = StreetProfiles.Vehicle(plate); + var check = new PlateCheck { Plate = vehicle.Plate }; + if (!vehicle.Registered) + { + check.Flags.Add(PlateFlag.Unregistered); + return check; + } + + if (vehicle.Stolen) check.Flags.Add(PlateFlag.Stolen); + if (vehicle.DriverIsOwner) return check; + + var owner = StreetProfiles.Person(vehicle.OwnerSeed, vehicle.OwnerFemale); + if (owner.Warrant is not null) check.Flags.Add(PlateFlag.Warrant); + if (owner.DriverLicense == StreetLicense.Suspended || owner.DriverLicense == StreetLicense.Revoked) check.Flags.Add(PlateFlag.Suspended); + return check; + } + } +} diff --git a/FivePRS.Core/Police/SpeedClock.cs b/FivePRS.Core/Police/SpeedClock.cs new file mode 100644 index 0000000..37a3d5f --- /dev/null +++ b/FivePRS.Core/Police/SpeedClock.cs @@ -0,0 +1,52 @@ +using System; +using FivePRS.Core.Civilian; + +namespace FivePRS.Core.Police +{ + public enum SpeedClockSource + { + FrontRadar, + RearRadar, + Lidar + } + + public sealed class SpeedClock + { + public const int MaxSpeed = 400; + public const int MaxDistance = 2_000; + public const int MaxModelLength = 40; + public const int MaxLocationLength = 80; + public const int KeepDays = 30; + + public int Id { get; set; } + public SpeedClockSource Source { get; set; } + public int Speed { get; set; } + public int? Fast { get; set; } + public string Units { get; set; } = "mph"; + public int? Distance { get; set; } + public string? Plate { get; set; } + public string? Model { get; set; } + public string Location { get; set; } = string.Empty; + public DateTime CreatedAt { get; set; } + + public bool Normalize() + { + if (!Enum.IsDefined(typeof(SpeedClockSource), Source) || Speed < 0 || Speed > MaxSpeed) return false; + + Units = Units == "kmh" ? "kmh" : "mph"; + Fast = Fast is > 0 and <= MaxSpeed && Fast > Speed ? Fast : null; + Distance = Source == SpeedClockSource.Lidar && Distance is >= 0 and <= MaxDistance ? Distance : null; + Plate = CivilianRules.TryNormalizePlate(Plate ?? string.Empty, out var plate) ? plate : null; + Model = Trim(Model, MaxModelLength); + Location = Trim(Location, MaxLocationLength) ?? string.Empty; + return true; + } + + private static string? Trim(string? text, int max) + { + var value = text?.Trim(); + if (string.IsNullOrEmpty(value)) return null; + return value!.Length > max ? value.Substring(0, max) : value; + } + } +} diff --git a/FivePRS.Core/Text/KeyCommands.cs b/FivePRS.Core/Text/KeyCommands.cs index 20642f5..f45d027 100644 --- a/FivePRS.Core/Text/KeyCommands.cs +++ b/FivePRS.Core/Text/KeyCommands.cs @@ -13,5 +13,11 @@ public static class KeyCommands public const string AiCallouts = "er_aicallouts"; public const string TrafficStop = "fiveprs_trafficstop"; public const string Backup = "fiveprs_request_backup"; + public const string Radar = "fiveprs_speed_radar"; + public const string RadarLock = "fiveprs_radarlock"; + public const string RadarRearLock = "fiveprs_radar_rearlock"; + public const string RadarRemote = "fiveprs_radar_remote"; + public const string PlateLock = "fiveprs_platelock"; + public const string Lidar = "fiveprs_lidar"; } } diff --git a/FivePRS.Police/Callouts/DomesticDisturbanceCallout.cs b/FivePRS.Police/Callouts/DomesticDisturbanceCallout.cs index bc6c703..d10ac2a 100644 --- a/FivePRS.Police/Callouts/DomesticDisturbanceCallout.cs +++ b/FivePRS.Police/Callouts/DomesticDisturbanceCallout.cs @@ -95,6 +95,19 @@ public override bool CanBeDispatched() public override async Task OnCalloutAccepted(CancellationToken ct) { + var blip = TrackBlip(World.CreateBlip(_scenePos)); + blip.Sprite = BlipSprite.Safehouse; + blip.Color = BlipColor.Orange; + blip.Name = "Domestic Disturbance"; + blip.IsShortRange = false; + blip.ShowRoute = true; + + ClientBrain.ShowNotification( + $"~b~Domestic Disturbance~w~ | Respond to scene. " + + (_profile == AggressorProfile.Armed ? "~r~Weapon reported~w~." : "")); + + await WaitForArrivalAsync(_scenePos, SpawnDistance, ct); + var aggModel = new Model(_aggressorModel); if (!await aggModel.Request(7_000)) { CalloutFailed(); return; } @@ -110,30 +123,30 @@ public override async Task OnCalloutAccepted(CancellationToken ct) vicModel.MarkAsNoLongerNeeded(); if (_victim is null || !_victim.Exists()) { CalloutFailed(); return; } - var blip = TrackBlip(World.CreateBlip(_scenePos)); - blip.Sprite = BlipSprite.Safehouse; - blip.Color = BlipColor.Orange; - blip.Name = "Domestic Disturbance"; - blip.IsShortRange = false; - blip.ShowRoute = true; - _aggressor.BlockPermanentEvents = true; _victim.BlockPermanentEvents = true; - API.TaskCombatPed(_aggressor.Handle, _victim.Handle, 0, 16); - - API.TaskSmartFleePed(_victim.Handle, _aggressor.Handle, 100f, -1, false, false); + API.TaskTurnPedToFaceEntity(_aggressor.Handle, _victim.Handle, -1); + API.TaskTurnPedToFaceEntity(_victim.Handle, _aggressor.Handle, -1); if (_profile == AggressorProfile.Armed) { API.GiveWeaponToPed(_aggressor.Handle, _threatWeapon, 1, false, true); } - ClientBrain.ShowNotification( - $"~b~Domestic Disturbance~w~ | Respond to scene. " + - (_profile == AggressorProfile.Armed ? "~r~Weapon reported~w~." : "")); + if (!await WaitUntilWitnessedAsync(_aggressor, ct)) + { + CalloutFailed(); + return; + } + + if (_profile != AggressorProfile.Peaceful && _victim.Exists()) + { + API.TaskCombatPed(_aggressor.Handle, _victim.Handle, 0, 16); + API.TaskSmartFleePed(_victim.Handle, _aggressor.Handle, 40f, -1, false, false); + } - bool arrived = await WaitForArrivalAsync(ct); + bool arrived = await WaitForSceneAsync(ct); if (!arrived) return; switch (_profile) @@ -150,14 +163,15 @@ public override async Task OnCalloutAccepted(CancellationToken ct) } } - private async Task WaitForArrivalAsync(CancellationToken ct) + private async Task WaitForSceneAsync(CancellationToken ct) { const float ArrivalDistM = 25.0f; const int PollMs = 500; while (!ct.IsCancellationRequested) { - var dist = Vector3.Distance(Game.PlayerPed.Position, _scenePos); + var target = _aggressor is not null && _aggressor.Exists() ? _aggressor.Position : _scenePos; + var dist = Vector3.Distance(Game.PlayerPed.Position, target); if (dist <= ArrivalDistM) return true; ClientBrain.ShowHelp($"~b~Scene~w~ ~y~{dist:F0}m~w~ away — respond Code 3", PollMs + 50); diff --git a/FivePRS.Police/Callouts/ShopliftingCallout.cs b/FivePRS.Police/Callouts/ShopliftingCallout.cs index 01f9659..d4710a8 100644 --- a/FivePRS.Police/Callouts/ShopliftingCallout.cs +++ b/FivePRS.Police/Callouts/ShopliftingCallout.cs @@ -40,6 +40,8 @@ public sealed class ShopliftingCallout : CalloutBase "a_f_y_scdressy_01", }; + private const float SpotDistance = 30f; + private readonly Random _rng = new(); private readonly Vector3 _storePosition; private readonly string _suspectModelName; @@ -71,11 +73,7 @@ public override async Task OnCalloutAccepted(CancellationToken ct) blip.IsShortRange = false; blip.ShowRoute = true; - const float ArrivalDistanceM = 40.0f; - while (Vector3.Distance(Game.PlayerPed.Position, _storePosition) > ArrivalDistanceM) - await Timing.WaitAsync(500, ct); - - ct.ThrowIfCancellationRequested(); + await WaitForArrivalAsync(_storePosition, SpawnDistance, ct); var model = new Model(_suspectModelName); if (!await model.Request(7_000)) @@ -96,7 +94,17 @@ public override async Task OnCalloutAccepted(CancellationToken ct) return; } - ClientBrain.ShowNotification($"~b~{Data.Name}~w~ | Suspect spotted, ~r~pursue on foot~w~."); + _suspect.BlockPermanentEvents = true; + _suspect.Task.WanderAround(_storePosition, 8f); + blip.ShowRoute = false; + + ClientBrain.ShowNotification($"~b~{Data.Name}~w~ | Suspect is still near the store. Find them."); + + if (!await WaitUntilWitnessedAsync(_suspect, ct, SpotDistance)) + { + CalloutFailed(); + return; + } await FootPursuitAsync(_suspect, catchDistM: 3.0f, escapeDistM: 300.0f, ct); } diff --git a/FivePRS.Police/Callouts/VehiclePursuitCallout.cs b/FivePRS.Police/Callouts/VehiclePursuitCallout.cs index d9c71cd..d83de2b 100644 --- a/FivePRS.Police/Callouts/VehiclePursuitCallout.cs +++ b/FivePRS.Police/Callouts/VehiclePursuitCallout.cs @@ -27,6 +27,8 @@ public sealed class VehiclePursuitCallout : CalloutBase private const int LostPursuitSec = 25; private const int SurrenderChancePct = 60; + private const float SpotDistM = 60.0f; + private const int SpotTimeoutSec = 180; private static readonly string[] StolenVehicles = { @@ -63,6 +65,7 @@ public sealed class VehiclePursuitCallout : CalloutBase private Ped? _driver; private DateTime _lastSeenTime = DateTime.UtcNow; + private bool _fleeing; public VehiclePursuitCallout() { @@ -72,17 +75,10 @@ public VehiclePursuitCallout() _plate = $"S{_rng.Next(10)}{_rng.Next(10)}{_rng.Next(10)} {(char)('A' + _rng.Next(26))}{(char)('A' + _rng.Next(26))}"; - var playerPos = Game.PlayerPed.Position; - var heading = Game.PlayerPed.Heading; - var fwd = new Vector3( - -(float)Math.Sin(heading * Math.PI / 180.0), - (float)Math.Cos(heading * Math.PI / 180.0), - 0f); - var roughSpawn = playerPos + fwd * (100f + _rng.Next(50)); - _spawnPos = World.GetNextPositionOnStreet(roughSpawn); + _spawnPos = World.GetNextPositionOnStreet(Positions.Around(Game.PlayerPed.Position, 350f + _rng.Next(250), _rng)); Data.Description = - $"Stolen vehicle reported — plate ~y~{_plate}~w~. Vehicle already in motion. Intercept and stop."; + $"Stolen vehicle spotted — plate ~y~{_plate}~w~. Locate the vehicle and attempt to stop it."; } public override Vector3 GetDispatchLocation() => _spawnPos; @@ -91,6 +87,22 @@ public VehiclePursuitCallout() public override async Task OnCalloutAccepted(CancellationToken ct) { + var areaBlip = TrackBlip(World.CreateBlip(_spawnPos)); + areaBlip.Sprite = BlipSprite.PersonalVehicleCar; + areaBlip.Color = BlipColor.Red; + areaBlip.Name = $"Last seen · {_plate}"; + areaBlip.IsShortRange = false; + areaBlip.ShowRoute = true; + + await WaitForArrivalAsync(_spawnPos, SpawnDistance, ct); + + var spawnPos = _spawnPos; + var spawnHeading = 0f; + if (API.GetClosestVehicleNodeWithHeading(_spawnPos.X, _spawnPos.Y, _spawnPos.Z, ref spawnPos, ref spawnHeading, 1, 3f, 0)) + spawnPos.Z += 0.5f; + else + spawnPos = _spawnPos; + var vehModel = new Model(_vehicleModel); if (!await vehModel.Request(7_000)) { @@ -98,7 +110,7 @@ public override async Task OnCalloutAccepted(CancellationToken ct) CalloutFailed(); return; } - _car = TrackEntity(await World.CreateVehicle(vehModel, _spawnPos, Game.PlayerPed.Heading)); + _car = TrackEntity(await World.CreateVehicle(vehModel, spawnPos, spawnHeading)); vehModel.MarkAsNoLongerNeeded(); if (_car is null || !_car.Exists()) { CalloutFailed(); return; } @@ -112,7 +124,7 @@ public override async Task OnCalloutAccepted(CancellationToken ct) CalloutFailed(); return; } - _driver = TrackEntity(await World.CreatePed(pedModel, _spawnPos, 0f)); + _driver = TrackEntity(await World.CreatePed(pedModel, spawnPos + new Vector3(0f, 0f, 2f), 0f)); pedModel.MarkAsNoLongerNeeded(); if (_driver is null || !_driver.Exists()) { CalloutFailed(); return; } @@ -120,8 +132,9 @@ public override async Task OnCalloutAccepted(CancellationToken ct) _driver.BlockPermanentEvents = true; _driver.IsInvincible = false; - BeginVehicleFlee(); + API.TaskVehicleDriveWander(_driver.Handle, _car.Handle, 15f, 786603); + areaBlip.Delete(); var blip = TrackBlip(_car.AttachBlip()); blip.Sprite = BlipSprite.PersonalVehicleCar; blip.Color = BlipColor.Red; @@ -129,16 +142,51 @@ public override async Task OnCalloutAccepted(CancellationToken ct) blip.ShowRoute = true; ClientBrain.ShowNotification( - $"~r~VEHICLE PURSUIT~w~ | Stolen {_vehicleModel.ToUpper()} · plate ~y~{_plate}~w~. " + - "Intercept and stop the vehicle!"); + $"~b~{Data.Name}~w~ | Stolen {_vehicleModel.ToUpper()} · plate ~y~{_plate}~w~ located. Close in."); + + if (!await WaitUntilSpottedAsync(ct)) return; + + BeginVehicleFlee(); + _lastSeenTime = DateTime.UtcNow; + + ClientBrain.ShowNotification( + $"~r~VEHICLE PURSUIT~w~ | Suspect is fleeing · plate ~y~{_plate}~w~. Stop the vehicle!"); await RunPursuitLoopAsync(ct); } + private async Task WaitUntilSpottedAsync(CancellationToken ct) + { + var deadline = DateTime.UtcNow.AddSeconds(SpotTimeoutSec); + + while (!ct.IsCancellationRequested) + { + if (_driver is null || !_driver.Exists() || _driver.IsDead || _car is null || !_car.Exists()) + { + CalloutFailed(); + return false; + } + + var dist = Vector3.Distance(Game.PlayerPed.Position, _car.Position); + if (dist <= CloseDistance || CanSee(_car, SpotDistM)) return true; + + if (dist > EscapeDistM && DateTime.UtcNow > deadline) + { + ClientBrain.ShowNotification("~r~Vehicle lost~w~ | The stolen vehicle left the area."); + CalloutFailed(); + return false; + } + + await Timing.WaitAsync(400, ct); + } + return false; + } + private void BeginVehicleFlee() { if (_driver is null || _car is null) return; + _fleeing = true; API.SetDriverAggressiveness(_driver.Handle, 1.0f); API.SetDriverAbility(_driver.Handle, 1.0f); API.TaskVehicleDriveToCoordLongrange( @@ -241,7 +289,7 @@ private Task RunFootPursuitAsync(CancellationToken ct) public override void OnUpdate() { - if (_car is null || !_car.Exists()) return; + if (!_fleeing || _car is null || !_car.Exists()) return; var dist = Vector3.Distance(Game.PlayerPed.Position, _car.Position); if (dist is > 5f and < 100f) { diff --git a/FivePRS.Police/Radar/LidarGun.cs b/FivePRS.Police/Radar/LidarGun.cs new file mode 100644 index 0000000..64dceed --- /dev/null +++ b/FivePRS.Police/Radar/LidarGun.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using CitizenFX.Core; +using CitizenFX.Core.Native; +using FivePRS.Client; +using FivePRS.Client.Agency; +using FivePRS.Core.Config; +using FivePRS.Core.Models; +using FivePRS.Core.Police; +using FivePRS.Core.Text; +using Newtonsoft.Json; + +namespace FivePRS.Police.Radar +{ + public class LidarGun : BaseScript + { + private const int AttackControl = 24; + private const int VehicleShapeFlags = 2; + private const int LspdTint = 5; + private const int ReticleComponent = 14; + private const uint Unarmed = 0xA2719263; + + private bool _on; + private bool _aiming; + private uint _device; + private bool _hadDevice; + private int _previousTint; + private uint _previousWeapon; + + public LidarGun() + { + API.RegisterCommand(KeyCommands.Lidar, new Action, string>((_, __, ___) => Toggle()), false); + API.RegisterKeyMapping(KeyCommands.Lidar, "FivePRS: Toggle lidar gun", "keyboard", "K"); + + EventHandlers["onClientResourceStop"] += new Action(name => + { + if (name == API.GetCurrentResourceName()) Stop(); + }); + } + + private static RadarSettings Settings => ConfigManager.Settings.Radar; + + private static bool CanUse => + BaseAgency.Active?.Department == Department.Police && Game.PlayerPed.Exists() && !Game.PlayerPed.IsDead && !Game.PlayerPed.IsInVehicle(); + + private void Toggle() + { + if (!Settings.Lidar) return; + if (_on) + { + Stop(); + return; + } + + if (!CanUse) + { + ClientBrain.ShowNotification("Use the lidar on foot while you're on duty with Police.", "~b~Lidar"); + return; + } + + var ped = Game.PlayerPed.Handle; + _device = Weapon(); + _previousWeapon = (uint)API.GetSelectedPedWeapon(ped); + _hadDevice = API.HasPedGotWeapon(ped, _device, false); + _previousTint = _hadDevice ? API.GetPedWeaponTintIndex(ped, _device) : 0; + + API.GiveWeaponToPed(ped, _device, 1, false, true); + if (IsDefaultWeapon) API.SetPedWeaponTintIndex(ped, _device, LspdTint); + API.SetCurrentPedWeapon(ped, _device, true); + + _on = true; + _aiming = false; + Send("show", new { units = Settings.Metric ? "KM/H" : "MPH", anchor = HudAnchor.Minimap() }); + Tick += OnTick; + } + + private bool IsDefaultWeapon => _device == (uint)API.GetHashKey(RadarSettings.DefaultLidarWeapon); + + private static uint Weapon() + { + var configured = (uint)API.GetHashKey(string.IsNullOrWhiteSpace(Settings.LidarWeapon) ? RadarSettings.DefaultLidarWeapon : Settings.LidarWeapon.Trim()); + return API.IsWeaponValid(configured) ? configured : (uint)API.GetHashKey(RadarSettings.DefaultLidarWeapon); + } + + private void Stop() + { + if (!_on) return; + _on = false; + Tick -= OnTick; + Send("hide", null); + + var ped = Game.PlayerPed; + if (!ped.Exists()) return; + + if (_hadDevice) + { + if (IsDefaultWeapon) API.SetPedWeaponTintIndex(ped.Handle, _device, _previousTint); + } + else API.RemoveWeaponFromPed(ped.Handle, _device); + var restore = _previousWeapon != _device && API.HasPedGotWeapon(ped.Handle, _previousWeapon, false) ? _previousWeapon : Unarmed; + API.SetCurrentPedWeapon(ped.Handle, restore, true); + } + + private async Task OnTick() + { + if (!CanUse || (uint)API.GetSelectedPedWeapon(Game.PlayerPed.Handle) != _device) + { + Stop(); + return; + } + + API.DisablePlayerFiring(API.PlayerId(), true); + API.DisableControlAction(0, AttackControl, true); + + var aiming = API.IsPlayerFreeAiming(API.PlayerId()); + if (aiming) API.HideHudComponentThisFrame(ReticleComponent); + if (aiming != _aiming) + { + _aiming = aiming; + Send("aim", new { aiming }); + } + + if (API.IsDisabledControlJustPressed(0, AttackControl)) Measure(); + await Task.FromResult(0); + } + + private void Measure() + { + var target = AimedVehicle() ?? RaycastVehicle(); + if (target is null) + { + Send("reading", new { miss = true }); + return; + } + + var distance = Vector3.Distance(Game.PlayerPed.Position, API.GetEntityCoords(target.Value, false)); + var speed = Settings.ToDisplaySpeed(API.GetEntitySpeed(target.Value)); + SpeedClocks.Record(SpeedClockSource.Lidar, speed, null, (int)Math.Round(distance), target.Value); + Send("reading", new + { + speed, + distance = (int)Math.Round(Settings.Metric ? distance : distance * 3.28084f), + distanceUnits = Settings.Metric ? "m" : "ft", + }); + } + + private static int? AimedVehicle() + { + var entity = 0; + if (!API.IsPlayerFreeAiming(API.PlayerId()) || !API.GetEntityPlayerIsFreeAimingAt(API.PlayerId(), ref entity) || entity == 0) + return null; + + if (API.IsEntityAVehicle(entity)) return entity; + if (API.IsEntityAPed(entity) && API.IsPedInAnyVehicle(entity, false)) return API.GetVehiclePedIsIn(entity, false); + return null; + } + + private static int? RaycastVehicle() + { + var origin = API.GetGameplayCamCoord(); + var rotation = API.GetGameplayCamRot(2); + var pitch = rotation.X * Math.PI / 180.0; + var yaw = rotation.Z * Math.PI / 180.0; + var direction = new Vector3( + (float)(-Math.Sin(yaw) * Math.Abs(Math.Cos(pitch))), + (float)(Math.Cos(yaw) * Math.Abs(Math.Cos(pitch))), + (float)Math.Sin(pitch)); + var end = origin + direction * Settings.LidarRange; + + var test = API.StartExpensiveSynchronousShapeTestLosProbe(origin.X, origin.Y, origin.Z, end.X, end.Y, end.Z, + VehicleShapeFlags, Game.PlayerPed.Handle, 7); + + var hit = false; + var position = Vector3.Zero; + var normal = Vector3.Zero; + var entity = 0; + API.GetShapeTestResult(test, ref hit, ref position, ref normal, ref entity); + return hit && entity != 0 && API.IsEntityAVehicle(entity) ? entity : null; + } + + private static void Send(string type, object? payload) => + API.SendNuiMessage(JsonConvert.SerializeObject(new { screen = "lidar", type, payload })); + } +} diff --git a/FivePRS.Police/Radar/RadarManager.cs b/FivePRS.Police/Radar/RadarManager.cs new file mode 100644 index 0000000..df7eb76 --- /dev/null +++ b/FivePRS.Police/Radar/RadarManager.cs @@ -0,0 +1,579 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using CitizenFX.Core; +using CitizenFX.Core.Native; +using FivePRS.Client; +using FivePRS.Client.Agency; +using FivePRS.Core.Config; +using FivePRS.Core.Events; +using FivePRS.Core.Models; +using FivePRS.Core.Police; +using FivePRS.Core.Text; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Serialization; + +namespace FivePRS.Police.Radar +{ + public class RadarManager : BaseScript + { + private const int UpdateMs = 200; + private const int PlateScanMs = 1_000; + private const int PlateMemoryMs = 120_000; + private const int EmergencyClass = 18; + private const float AntennaCone = 0.97f; + private const float PlateCone = 0.95f; + private const float MovingSpeed = 1f; + private const float TurnErrorDegrees = 7f; + private const string Subject = "~b~ALPR"; + private const string WatchFlag = "watch"; + private const string SharedKey = "fiveprsRadar"; + private const int DriverSeat = -1; + private const string OperatorCallback = "radarOperator"; + private const string RemoteClosedCallback = "radarRemoteClosed"; + + private static readonly JsonSerializerSettings JsonSettings = new() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; + + private static readonly Dictionary FlagNames = new() + { + [PlateFlag.Stolen] = "Stolen vehicle", + [PlateFlag.Warrant] = "Owner has a warrant", + [PlateFlag.Unregistered] = "Unregistered", + [PlateFlag.Suspended] = "Owner's license suspended", + [WatchFlag] = "On your watch list", + }; + + private sealed class Reading + { + public int? Target { get; set; } + public int? Fast { get; set; } + public string? Direction { get; set; } + public bool Error { get; set; } + public int Vehicle { get; set; } + } + + private sealed class Antenna + { + public Antenna(string name, float sign) + { + Name = name; + Sign = sign; + } + + public string Name { get; } + public float Sign { get; } + public Reading Reading { get; set; } = new(); + public bool Locked { get; set; } + } + + private sealed class PlateRead + { + public string Plate { get; set; } = string.Empty; + public string? Model { get; set; } + public List Flags { get; set; } = new(); + public bool Checked { get; set; } + public bool Watched { get; set; } + public int Style { get; set; } + } + + private readonly Dictionary _recentPlates = new(); + private readonly Dictionary _plateDirection = new(); + private readonly Dictionary _reads = new(); + private readonly Antenna _front = new("front", 1f); + private readonly Antenna _rear = new("rear", -1f); + + private RadarOperator? _operator; + private bool _on; + private bool _shown; + private bool _remoteOpen; + private bool _platesLocked; + private bool _viewing; + private Vehicle? _sharedVehicle; + private string _sharedPayload = string.Empty; + private float? _lastHeading; + private int _nextPlateScan; + private string _lastPayload = string.Empty; + + public RadarManager() + { + API.RegisterCommand(KeyCommands.Radar, new Action, string>((_, __, ___) => Toggle()), false); + API.RegisterKeyMapping(KeyCommands.Radar, "FivePRS: Toggle radar", "keyboard", "F7"); + API.RegisterCommand(KeyCommands.RadarLock, new Action, string>((_, __, ___) => ToggleLock(_front)), false); + API.RegisterKeyMapping(KeyCommands.RadarLock, "FivePRS: Lock front radar antenna", "keyboard", "J"); + API.RegisterCommand(KeyCommands.RadarRearLock, new Action, string>((_, __, ___) => ToggleLock(_rear)), false); + API.RegisterKeyMapping(KeyCommands.RadarRearLock, "FivePRS: Lock rear radar antenna", "keyboard", "U"); + API.RegisterCommand(KeyCommands.RadarRemote, new Action, string>((_, __, ___) => OpenRemote()), false); + API.RegisterKeyMapping(KeyCommands.RadarRemote, "FivePRS: Radar operator menu", "keyboard", "F9"); + API.RegisterCommand(KeyCommands.PlateLock, new Action, string>((_, __, ___) => TogglePlateLock()), false); + API.RegisterKeyMapping(KeyCommands.PlateLock, "FivePRS: Lock plate reader", "keyboard", "O"); + + API.RegisterNuiCallbackType(OperatorCallback); + EventHandlers[$"__cfx_nui:{OperatorCallback}"] += new Action, CallbackDelegate>(OnOperatorChanged); + API.RegisterNuiCallbackType(RemoteClosedCallback); + EventHandlers[$"__cfx_nui:{RemoteClosedCallback}"] += new Action, CallbackDelegate>((_, callback) => + { + CloseRemote(); + callback("ok"); + }); + + EventHandlers[EventNames.ClientPlateRead] += new Action(OnPlateRead); + EventHandlers[EventNames.ClientRadarControl] += new Action(OnRemoteControl); + EventHandlers["onClientResourceStop"] += new Action(name => + { + if (name != API.GetCurrentResourceName()) return; + CloseRemote(); + Hide(); + }); + + Tick += OnTick; + } + + private static RadarSettings Settings => ConfigManager.Settings.Radar; + + private RadarOperator Operator => _operator ??= RadarOperator.Load(Settings.SpeedAlert); + + private static bool OnDutyAsPolice => BaseAgency.Active?.Department == Department.Police; + + private void Toggle() + { + if (!Settings.Enabled) return; + if (_viewing || (PatrolCar() is { } car && !IsDriver(car))) + { + ClientBrain.ShowNotification("The driver turns the radar on and off.", "~b~Radar"); + return; + } + if (!OnDutyAsPolice || PatrolCar() is null) + { + ClientBrain.ShowNotification("The radar works from a patrol car while you're on duty with Police.", "~b~Radar"); + return; + } + + _on = !_on; + _front.Locked = false; + _rear.Locked = false; + _platesLocked = false; + if (!_on) + { + CloseRemote(); + Hide(); + } + } + + private void ToggleLock(Antenna antenna) + { + if (_viewing) + { + ClientEvents.TriggerServer(EventNames.ServerRadarControl, antenna.Name); + return; + } + if (!_on || !_shown) return; + antenna.Locked = !antenna.Locked; + Sound(antenna.Locked ? "lock" : "unlock"); + if (antenna.Locked) Clock(antenna); + Send(true); + } + + private void TogglePlateLock() + { + if (_viewing) + { + ClientEvents.TriggerServer(EventNames.ServerRadarControl, "plates"); + return; + } + if (!_on || !_shown || !Settings.PlateReader) return; + _platesLocked = !_platesLocked; + Sound(_platesLocked ? "lock" : "unlock"); + Send(true); + } + + private void OnRemoteControl(string control) + { + if (!_on || !_shown) return; + if (control == "front") ToggleLock(_front); + else if (control == "rear") ToggleLock(_rear); + else if (control == "plates") TogglePlateLock(); + } + + private void OpenRemote() + { + if (!Settings.Enabled) return; + if (!_on && !_viewing) + { + ClientBrain.ShowNotification("Turn the radar on first.", "~b~Radar"); + return; + } + + _remoteOpen = true; + API.SetNuiFocus(true, true); + API.SendNuiMessage(JsonConvert.SerializeObject(new { screen = "radar", type = "remote", payload = Operator }, JsonSettings)); + } + + private void CloseRemote() + { + if (!_remoteOpen) return; + _remoteOpen = false; + API.SetNuiFocus(false, false); + API.SendNuiMessage("{\"screen\":\"radar\",\"type\":\"closeRemote\"}"); + } + + private void OnOperatorChanged(IDictionary data, CallbackDelegate callback) + { + var updated = JObject.FromObject(data).ToObject(); + if (updated is not null) + { + _operator = updated.Clamped(); + _operator.Save(); + Send(true); + } + callback("ok"); + } + + private static bool IsDriver(Vehicle vehicle) => API.GetPedInVehicleSeat(vehicle.Handle, DriverSeat) == Game.PlayerPed.Handle; + + private static bool HasPlayerPassenger(Vehicle vehicle) + { + var seats = API.GetVehicleMaxNumberOfPassengers(vehicle.Handle); + for (var seat = 0; seat < seats; seat++) + { + var ped = API.GetPedInVehicleSeat(vehicle.Handle, seat); + if (ped != 0 && ped != Game.PlayerPed.Handle && API.IsPedAPlayer(ped)) return true; + } + return false; + } + + private static Vehicle? PatrolCar() + { + var vehicle = Game.PlayerPed.CurrentVehicle; + return vehicle is not null && vehicle.Exists() && API.GetVehicleClass(vehicle.Handle) == EmergencyClass ? vehicle : null; + } + + private async Task OnTick() + { + await Delay(UpdateMs); + + var vehicle = PatrolCar(); + if (vehicle is not null && Settings.Enabled && OnDutyAsPolice && !IsDriver(vehicle)) + { + if (_on) + { + _on = false; + Hide(); + } + ShowShared(vehicle); + return; + } + + if (_viewing) + { + _viewing = false; + CloseRemote(); + Hide(); + } + + if (!_on || !Settings.Enabled || !OnDutyAsPolice || vehicle is null) + { + if (_on && (!OnDutyAsPolice || vehicle is null)) + { + _on = false; + CloseRemote(); + } + Hide(); + return; + } + + var error = Unstable(vehicle); + Update(_front, Operator.Front, vehicle, error); + Update(_rear, Operator.Rear, vehicle, error); + + var now = API.GetGameTimer(); + if (Settings.PlateReader && !_platesLocked && now >= _nextPlateScan) + { + _nextPlateScan = now + PlateScanMs; + ScanPlate(vehicle, "front", now); + ScanPlate(vehicle, "rear", now); + Forget(now); + } + + Send(false); + } + + private bool Unstable(Vehicle own) + { + var heading = own.Heading; + var turning = _lastHeading.HasValue && Math.Abs(((heading - _lastHeading.Value + 540f) % 360f) - 180f) > TurnErrorDegrees; + _lastHeading = heading; + return turning || !API.IsVehicleOnAllWheels(own.Handle); + } + + private void Update(Antenna antenna, RadarAntennaSetup setup, Vehicle own, bool error) + { + if (antenna.Locked) return; + if (!setup.Xmit) + { + antenna.Reading = new Reading(); + return; + } + + antenna.Reading = error ? new Reading { Error = true } : Measure(own, antenna.Sign, setup.Mode); + + var limit = Operator.FastLimit; + var fastest = Math.Max(antenna.Reading.Target ?? 0, antenna.Reading.Fast ?? 0); + if (Operator.FastLock && limit > 0 && fastest >= limit) + { + antenna.Locked = true; + Sound("fast"); + Clock(antenna); + } + } + + private static void Clock(Antenna antenna) + { + var reading = antenna.Reading; + if (reading.Error || reading.Target is not { } speed) return; + var source = antenna.Sign > 0f ? SpeedClockSource.FrontRadar : SpeedClockSource.RearRadar; + SpeedClocks.Record(source, speed, reading.Fast, null, reading.Vehicle); + } + + private static Reading Measure(Vehicle own, float sign, string mode) + { + var reading = new Reading(); + var closest = Settings.Range; + var fastest = -1f; + var targetSpeed = -1f; + var ownVelocity = own.Velocity; + var forward = own.ForwardVector; + + foreach (var vehicle in World.GetAllVehicles()) + { + if (vehicle.Handle == own.Handle || !vehicle.Exists()) continue; + + var offset = vehicle.Position - own.Position; + var distance = offset.Length(); + if (distance > Settings.Range || distance < 2f) continue; + + offset.Normalize(); + if (Vector3.Dot(offset, forward) * sign < AntennaCone) continue; + + var velocity = vehicle.Velocity; + var speed = velocity.Length(); + if (speed < MovingSpeed) continue; + + var same = Vector3.Dot(velocity, forward) > 0f; + if (same != (mode == RadarOperator.Same)) continue; + + if (distance < closest) + { + closest = distance; + targetSpeed = speed; + reading.Target = Settings.ToDisplaySpeed(speed); + reading.Vehicle = vehicle.Handle; + reading.Direction = Vector3.Dot(velocity - ownVelocity, offset) < 0f ? "approach" : "recede"; + } + if (speed > fastest) fastest = speed; + } + + if (fastest > targetSpeed && reading.Target.HasValue && Settings.ToDisplaySpeed(fastest) > reading.Target) + reading.Fast = Settings.ToDisplaySpeed(fastest); + + return reading; + } + + private void ScanPlate(Vehicle own, string direction, int now) + { + var sign = direction == "front" ? 1f : -1f; + Vehicle? nearest = null; + var closest = Settings.PlateReaderRange; + + foreach (var vehicle in World.GetAllVehicles()) + { + if (vehicle.Handle == own.Handle || !vehicle.Exists()) continue; + + var offset = vehicle.Position - own.Position; + var distance = offset.Length(); + if (distance > closest || distance < 2f) continue; + + offset.Normalize(); + if (Vector3.Dot(offset, own.ForwardVector) * sign < PlateCone) continue; + + nearest = vehicle; + closest = distance; + } + + if (nearest is null) return; + + var plate = StreetIdentity.PlateOf(nearest); + if (plate.Length == 0) return; + + _plateDirection[direction] = plate; + if (_recentPlates.TryGetValue(plate, out var seen) && now - seen < PlateMemoryMs) return; + + _recentPlates[plate] = now; + var read = new PlateRead + { + Plate = plate, + Model = StreetIdentity.VehicleName(nearest), + Style = API.GetVehicleNumberPlateTextIndex(nearest.Handle), + Watched = Operator.Watching(plate), + }; + _reads[plate] = read; + if (read.Watched) + { + read.Flags.Add(WatchFlag); + Alert(read); + } + ClientEvents.TriggerServer(EventNames.ServerPlateRead, plate); + } + + private void Alert(PlateRead read) + { + var reasons = string.Join(" · ", read.Flags.Select(flag => FlagNames.TryGetValue(flag, out var name) ? name : flag)); + ClientBrain.ShowNotification($"~r~HIT~w~ {read.Plate} · {read.Model}~n~{reasons}", Subject); + Sound("hit"); + } + + private void Forget(int now) + { + foreach (var plate in _recentPlates.Where(entry => now - entry.Value >= PlateMemoryMs).Select(entry => entry.Key).ToList()) + { + _recentPlates.Remove(plate); + if (!_plateDirection.ContainsValue(plate)) _reads.Remove(plate); + } + } + + private void OnPlateRead(string json) + { + var check = JsonConvert.DeserializeObject(json); + if (check is null) return; + + var key = _reads.Keys.FirstOrDefault(plate => string.Equals(plate.Replace(" ", string.Empty), check.Plate.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)); + if (key is null) return; + + var read = _reads[key]; + read.Flags = check.Flags.ToList(); + if (read.Watched) read.Flags.Add(WatchFlag); + read.Checked = true; + if (!string.IsNullOrEmpty(check.Model) && check.Model != "Unknown") read.Model = check.Model; + + if (check.Flags.Count > 0) Alert(read); + Send(true); + } + + private object? PlatePayload(string direction) + { + if (!_plateDirection.TryGetValue(direction, out var plate) || !_reads.TryGetValue(plate, out var read)) return null; + return new { read.Plate, read.Model, read.Flags, read.Checked, read.Style }; + } + + private object AntennaPayload(Antenna antenna, RadarAntennaSetup setup) + { + var limit = Operator.FastLimit; + var reading = antenna.Reading; + return new + { + setup.Xmit, + setup.Mode, + reading.Target, + reading.Fast, + reading.Direction, + reading.Error, + antenna.Locked, + Alert = limit > 0 && Math.Max(reading.Target ?? 0, reading.Fast ?? 0) >= limit, + }; + } + + private void Send(bool force) + { + var vehicle = PatrolCar(); + var op = Operator; + var payload = JsonConvert.SerializeObject(new + { + Units = Settings.Metric ? "KM/H" : "MPH", + Patrol = vehicle is null ? 0 : Settings.ToDisplaySpeed(vehicle.Speed), + Front = AntennaPayload(_front, op.Front), + Rear = AntennaPayload(_rear, op.Rear), + op.FastLimit, + op.FastLock, + PlateReader = Settings.PlateReader, + PlatesLocked = _platesLocked, + Anchor = HudAnchor.Minimap(), + Layout = new { op.X, op.Y, op.Scale }, + Audio = new { op.Doppler, op.Beep }, + Plates = new { Front = PlatePayload("front"), Rear = PlatePayload("rear") }, + }, JsonSettings); + + if (vehicle is not null) Share(vehicle, payload); + if (!force && _shown && payload == _lastPayload) return; + _lastPayload = payload; + _shown = true; + API.SendNuiMessage("{\"screen\":\"radar\",\"type\":\"show\",\"payload\":" + payload + "}"); + } + + private void Share(Vehicle vehicle, string payload) + { + if (!HasPlayerPassenger(vehicle)) + { + StopSharing(); + return; + } + + if (_sharedVehicle?.Handle == vehicle.Handle && payload == _sharedPayload) return; + _sharedVehicle = vehicle; + _sharedPayload = payload; + vehicle.State.Set(SharedKey, payload, true); + } + + private void StopSharing() + { + if (_sharedVehicle is null) return; + if (_sharedVehicle.Exists()) _sharedVehicle.State.Set(SharedKey, null, true); + _sharedVehicle = null; + _sharedPayload = string.Empty; + } + + private void ShowShared(Vehicle vehicle) + { + object? raw = vehicle.State.Get(SharedKey); + var shared = raw as string; + if (string.IsNullOrEmpty(shared)) + { + if (!_viewing) return; + _viewing = false; + CloseRemote(); + Hide(); + return; + } + + var state = JObject.Parse(shared!); + var op = Operator; + var serializer = JsonSerializer.Create(JsonSettings); + state["layout"] = JObject.FromObject(new { op.X, op.Y, op.Scale }, serializer); + state["audio"] = JObject.FromObject(new { op.Doppler, op.Beep }, serializer); + state["anchor"] = JObject.FromObject(HudAnchor.Minimap()); + state["passenger"] = true; + + _viewing = true; + var payload = state.ToString(Formatting.None); + if (_shown && payload == _lastPayload) return; + _lastPayload = payload; + _shown = true; + API.SendNuiMessage("{\"screen\":\"radar\",\"type\":\"show\",\"payload\":" + payload + "}"); + } + + private void Sound(string kind) => + API.SendNuiMessage(JsonConvert.SerializeObject(new { screen = "radar", type = "sound", payload = new { kind, volume = Operator.Beep } })); + + private void Hide() + { + _lastHeading = null; + StopSharing(); + if (!_shown) return; + _shown = false; + _lastPayload = string.Empty; + _platesLocked = false; + _plateDirection.Clear(); + API.SendNuiMessage("{\"screen\":\"radar\",\"type\":\"hide\"}"); + } + } +} diff --git a/FivePRS.Police/Radar/RadarOperator.cs b/FivePRS.Police/Radar/RadarOperator.cs new file mode 100644 index 0000000..48a9ed8 --- /dev/null +++ b/FivePRS.Police/Radar/RadarOperator.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using CitizenFX.Core.Native; +using Newtonsoft.Json; + +namespace FivePRS.Police.Radar +{ + public sealed class RadarAntennaSetup + { + public bool Xmit { get; set; } = true; + public string Mode { get; set; } = RadarOperator.Same; + } + + public sealed class RadarOperator + { + public const string Same = "same"; + public const string Opposite = "opp"; + + private const string Key = "fiveprs:radar"; + private const int WatchLimit = 25; + + public RadarAntennaSetup Front { get; set; } = new() { Mode = Opposite }; + public RadarAntennaSetup Rear { get; set; } = new(); + public int FastLimit { get; set; } = -1; + public bool FastLock { get; set; } + public int Doppler { get; set; } = 40; + public int Beep { get; set; } = 70; + public int Scale { get; set; } = 100; + public float? X { get; set; } + public float? Y { get; set; } + public List Watch { get; set; } = new(); + + public static RadarOperator Load(int defaultFastLimit) + { + RadarOperator? loaded = null; + try + { + var json = API.GetResourceKvpString(Key); + if (!string.IsNullOrEmpty(json)) loaded = JsonConvert.DeserializeObject(json); + } + catch (JsonException) + { + } + + var result = loaded ?? new RadarOperator(); + if (result.FastLimit < 0) result.FastLimit = defaultFastLimit; + return result.Clamped(); + } + + public static string NormalizePlate(string? plate) => + new string((plate ?? string.Empty).Where(char.IsLetterOrDigit).Take(8).ToArray()).ToUpperInvariant(); + + public bool Watching(string plate) => Watch.Contains(NormalizePlate(plate)); + + public void Save() => API.SetResourceKvp(Key, JsonConvert.SerializeObject(Clamped())); + + public RadarOperator Clamped() + { + Front ??= new RadarAntennaSetup(); + Rear ??= new RadarAntennaSetup { Mode = Same }; + Front.Mode = Front.Mode == Same ? Same : Opposite; + Rear.Mode = Rear.Mode == Opposite ? Opposite : Same; + FastLimit = Math.Max(0, Math.Min(250, FastLimit)); + Doppler = Math.Max(0, Math.Min(100, Doppler)); + Beep = Math.Max(0, Math.Min(100, Beep)); + Scale = Math.Max(60, Math.Min(160, Scale)); + if (X.HasValue) X = Math.Max(0f, Math.Min(0.95f, X.Value)); + if (Y.HasValue) Y = Math.Max(0f, Math.Min(0.95f, Y.Value)); + Watch = (Watch ?? new List()).Select(NormalizePlate).Where(plate => plate.Length > 0).Distinct().Take(WatchLimit).ToList(); + return this; + } + } +} diff --git a/FivePRS.Police/Radar/SpeedClocks.cs b/FivePRS.Police/Radar/SpeedClocks.cs new file mode 100644 index 0000000..c3ab851 --- /dev/null +++ b/FivePRS.Police/Radar/SpeedClocks.cs @@ -0,0 +1,37 @@ +using CitizenFX.Core; +using CitizenFX.Core.Native; +using FivePRS.Client; +using FivePRS.Core.Config; +using FivePRS.Core.Events; +using FivePRS.Core.Police; +using Newtonsoft.Json; + +namespace FivePRS.Police.Radar +{ + internal static class SpeedClocks + { + public static void Record(SpeedClockSource source, int speed, int? fast, int? distance, int vehicle) + { + string? plate = null, model = null; + if (vehicle != 0 && API.DoesEntityExist(vehicle) && API.IsEntityAVehicle(vehicle)) + { + var target = new Vehicle(vehicle); + plate = StreetIdentity.PlateOf(target); + model = StreetIdentity.VehicleName(target); + } + + var clock = new SpeedClock + { + Source = source, + Speed = speed, + Fast = fast, + Units = ConfigManager.Settings.Radar.Metric ? "kmh" : "mph", + Distance = distance, + Plate = plate, + Model = model, + Location = Reports.Describe(Game.PlayerPed.Position), + }; + ClientEvents.TriggerServer(EventNames.ServerSpeedClock, JsonConvert.SerializeObject(clock)); + } + } +} diff --git a/FivePRS.Police/TrafficStops/TrafficStop.cs b/FivePRS.Police/TrafficStops/TrafficStop.cs index 50f1a23..1c500a7 100644 --- a/FivePRS.Police/TrafficStops/TrafficStop.cs +++ b/FivePRS.Police/TrafficStops/TrafficStop.cs @@ -26,6 +26,10 @@ public sealed class TrafficStop private const float PullOverSpeed = 7f; private const float RoadsideOffset = 3.5f; private const float AheadDistance = 22f; + private const float MinTargetDistance = 8f; + private const float MaxTargetDistance = 40f; + private const float MinTargetAlignment = 0.5f; + private const float MaxPullOverTravel = 50f; private readonly Blip _blip; @@ -92,14 +96,46 @@ public TrafficStop(Ped driver, Vehicle? vehicle, int seed) public RecordInfo[] ActiveWarrants => Identity?.Records.Where(r => r.Type == RecordType.Warrant && r.Active).ToArray() ?? new RecordInfo[0]; + private Vector3 _pullOverStart; + private Vector3 _pullOverHeading; + public void PullOver() { if (Vehicle is null) return; - var target = Vehicle.Position + Vehicle.ForwardVector * AheadDistance + Vehicle.RightVector * RoadsideOffset; + _pullOverStart = Vehicle.Position; + _pullOverHeading = Vehicle.ForwardVector; API.SetVehicleIndicatorLights(Vehicle.Handle, RightIndicator, true); - API.TaskVehicleDriveToCoordLongrange(Driver.Handle, Vehicle.Handle, target.X, target.Y, target.Z, - PullOverSpeed, NormalDrivingStyle, 2f); + + var ahead = Vehicle.Position + Vehicle.ForwardVector * AheadDistance; + var target = ahead + Vehicle.RightVector * RoadsideOffset; + var roadside = Vector3.Zero; + if (API.GetRoadSidePointWithHeading(ahead.X, ahead.Y, ahead.Z, Vehicle.Heading, ref roadside) && IsAhead(roadside)) + target = roadside; + + if (!IsAhead(target)) + { + API.TaskVehicleTempAction(Driver.Handle, Vehicle.Handle, BrakeAction, int.MaxValue); + return; + } + + API.TaskVehicleDriveToCoord(Driver.Handle, Vehicle.Handle, target.X, target.Y, target.Z, + PullOverSpeed, 0, (uint)Vehicle.Model.Hash, NormalDrivingStyle, 2f, 0f); + } + + public bool StrayedWhilePullingOver => + Vehicle is not null && Vehicle.Exists() && + (Vector3.Distance(Vehicle.Position, _pullOverStart) > MaxPullOverTravel || + Vector3.Dot(Vehicle.ForwardVector, _pullOverHeading) < MinTargetAlignment); + + private bool IsAhead(Vector3 target) + { + var offset = target - Vehicle!.Position; + var distance = offset.Length(); + if (distance < MinTargetDistance || distance > MaxTargetDistance) return false; + + offset.Normalize(); + return Vector3.Dot(offset, Vehicle.ForwardVector) >= MinTargetAlignment; } public void Hold() diff --git a/FivePRS.Police/TrafficStops/TrafficStopManager.cs b/FivePRS.Police/TrafficStops/TrafficStopManager.cs index 512015e..e29c486 100644 --- a/FivePRS.Police/TrafficStops/TrafficStopManager.cs +++ b/FivePRS.Police/TrafficStops/TrafficStopManager.cs @@ -210,7 +210,7 @@ private async Task UpdateStopAsync(TrafficStop stop) stop.Flee(); ClientBrain.ShowNotification($"~r~The driver is fleeing!~w~ Pursue the ~y~{stop.Model}~w~.", Subject); } - else if ((stop.Vehicle!.Speed < 0.5f && elapsed > 2_000) || elapsed > PullOverTimeoutMs) + else if ((stop.Vehicle!.Speed < 0.5f && elapsed > 2_000) || elapsed > PullOverTimeoutMs || stop.StrayedWhilePullingOver) { stop.Hold(); ClientBrain.ShowNotification($"Vehicle stopped. Approach the driver and press {Binds.Interact}.", Subject); diff --git a/FivePRS.Server/Civilian/CivilianService.cs b/FivePRS.Server/Civilian/CivilianService.cs index 7d69dc1..4dd5975 100644 --- a/FivePRS.Server/Civilian/CivilianService.cs +++ b/FivePRS.Server/Civilian/CivilianService.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FivePRS.Core.Civilian; @@ -27,10 +28,17 @@ public CivilianService(CivilianStore store, PhotoStore photos, Func $"{what} are managed by {ManagedBy}."; + public async Task GetStateAsync(string owner) { var characters = await _store.GetCharactersAsync(owner); var active = characters.OrderByDescending(c => c.LastUsedAt).ThenByDescending(c => c.Id).FirstOrDefault(); + if (ManagedBy is not null) + characters = active?.ExternalId is null ? new List() : new List { active }; + if (ManagedBy is not null && active?.ExternalId is null) active = null; var state = new CivilianState { @@ -38,6 +46,7 @@ public async Task GetStateAsync(string owner) ActiveCharacterId = active?.Id, MaxCharacters = _settings().MaxCharacters, MaxVehicles = _settings().MaxVehiclesPerCharacter, + ManagedBy = ManagedBy, }; var held = active is null ? null : await _store.GetLicensesAsync(active.Id); @@ -59,11 +68,13 @@ public async Task GetStateAsync(string owner) public async Task GetActiveCharacterAsync(string owner) { var characters = await _store.GetCharactersAsync(owner); - return characters.OrderByDescending(c => c.LastUsedAt).ThenByDescending(c => c.Id).FirstOrDefault(); + var active = characters.OrderByDescending(c => c.LastUsedAt).ThenByDescending(c => c.Id).FirstOrDefault(); + return ManagedBy is not null && active?.ExternalId is null ? null : active; } public async Task CreateCharacterAsync(string owner, string? firstName, string? lastName, string? dateOfBirth, string? gender) { + if (ManagedBy is not null) return Managed("Characters"); if (!CivilianRules.TryNormalizeName(firstName, out var first) || !CivilianRules.TryNormalizeName(lastName, out var last)) return $"Names must be 1 to {CivilianRules.MaxNameLength} letters; spaces, hyphens and apostrophes are allowed."; @@ -90,6 +101,7 @@ await _store.CreateCharacterAsync(new CharacterInfo public async Task SelectCharacterAsync(string owner, int characterId) { + if (ManagedBy is not null) return Managed("Characters"); if (await GetOwnedCharacterAsync(owner, characterId) is null) return "Character not found."; await _store.TouchCharacterAsync(characterId); @@ -98,6 +110,7 @@ await _store.CreateCharacterAsync(new CharacterInfo public async Task DeleteCharacterAsync(string owner, int characterId) { + if (ManagedBy is not null) return Managed("Characters"); if (await GetOwnedCharacterAsync(owner, characterId) is null) return "Character not found."; var summary = await _store.GetSummaryAsync(characterId); @@ -170,6 +183,7 @@ await _store.CreateCharacterAsync(new CharacterInfo public async Task RegisterVehicleAsync(string owner, string? plate, string? model) { + if (ManagedBy is not null) return Managed("Vehicles"); var character = await GetActiveCharacterAsync(owner); if (character is null) return "Create a character first."; @@ -204,6 +218,7 @@ await _store.AddVehicleAsync(new VehicleInfo public async Task RemoveVehicleAsync(string owner, int vehicleId) { + if (ManagedBy is not null) return Managed("Vehicles"); if (await GetOwnedVehicleAsync(owner, vehicleId) is null) return "Vehicle not found."; await _store.DeleteVehicleAsync(vehicleId); diff --git a/FivePRS.Server/Civilian/LookupService.cs b/FivePRS.Server/Civilian/LookupService.cs index 7d4e987..d57ffc3 100644 --- a/FivePRS.Server/Civilian/LookupService.cs +++ b/FivePRS.Server/Civilian/LookupService.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using FivePRS.Core.Civilian; using FivePRS.Core.Config; +using FivePRS.Core.Police; using FivePRS.Server.Database; namespace FivePRS.Server.Civilian @@ -24,6 +25,10 @@ public LookupService(CivilianStore store, PhotoStore photos, Func>? ExternalPlate { get; set; } + + public bool CollectsFines { get; set; } + public async Task<(LookupResult? Result, string? Error)> SearchByNameAsync(string? term) { if (!CivilianRules.TryNormalizeSearch(term, out var normalized)) @@ -39,6 +44,8 @@ public LookupService(CivilianStore store, PhotoStore photos, Func CheckPlateAsync(string plate) + { + var vehicle = await _store.GetVehicleByPlateAsync(plate); + if (vehicle is null && ExternalPlate is not null && await ExternalPlate(plate)) + vehicle = await _store.GetVehicleByPlateAsync(plate); + if (vehicle is null) return PlateFlags.FromProfile(plate); + + return PlateFlags.FromRecord(plate, vehicle, await BuildRecordAsync(vehicle.CharacterId)); + } + public async Task<(LookupResult? Result, string? Error)> GetRecordAsync(int characterId) { var record = await BuildRecordAsync(characterId); @@ -58,7 +75,8 @@ public LookupService(CivilianStore store, PhotoStore photos, Func 0 && CollectsFines && character.ExternalId is not null ? FineStatus.Unpaid : FineStatus.None, }, officer.License); return null; diff --git a/FivePRS.Server/Civilian/StreetService.cs b/FivePRS.Server/Civilian/StreetService.cs index ffbfcc5..0e481da 100644 --- a/FivePRS.Server/Civilian/StreetService.cs +++ b/FivePRS.Server/Civilian/StreetService.cs @@ -36,7 +36,7 @@ public StreetService(CivilianStore store, LookupService lookup) { if (!CivilianRules.TryNormalizePlate(plate, out var normalized)) return (null, "That plate can't be read."); - if (await _store.GetVehicleByPlateAsync(normalized) is null) + if (await _store.GetVehicleByPlateAsync(normalized) is null && !(_lookup.ExternalPlate is not null && await _lookup.ExternalPlate(normalized))) { var vehicle = StreetProfiles.Vehicle(normalized); if (!vehicle.Registered) return (null, $"No registration found for {normalized}."); diff --git a/FivePRS.Server/ConfigLayout.cs b/FivePRS.Server/ConfigLayout.cs index 3113cee..2e06362 100644 --- a/FivePRS.Server/ConfigLayout.cs +++ b/FivePRS.Server/ConfigLayout.cs @@ -16,11 +16,14 @@ public static void Update(string resourcePath) { var moved = MoveLegacyFiles(resourcePath); var created = CreateMissingRanks(resourcePath); + var named = CreateMissingInfo(resourcePath); if (moved > 0) Log.Info($"Moved {moved} config files into config/departments, config/world and config/civilian."); if (created > 0) Log.Info($"Added ranks.json for {created} departments. Edit it to rename ranks or change promotion XP."); + if (named > 0) + Log.Info($"Added department.json for {named} departments. Edit it to rename a department or change its icon."); } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { @@ -67,6 +70,22 @@ public static int CreateMissingRanks(string resourcePath) return created; } + public static int CreateMissingInfo(string resourcePath) + { + var created = 0; + foreach (var department in ConfigManager.Departments) + { + var path = Resolve(resourcePath, ConfigFiles.Department(department, ConfigFiles.Info)); + if (File.Exists(path)) continue; + + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, Serialize(ConfigManager.DefaultInfo(department))); + created++; + } + + return created; + } + private static string Serialize(object value) { using var text = new StringWriter(); diff --git a/FivePRS.Server/Database/CivilianStore.cs b/FivePRS.Server/Database/CivilianStore.cs index 1b486e3..357cbcf 100644 --- a/FivePRS.Server/Database/CivilianStore.cs +++ b/FivePRS.Server/Database/CivilianStore.cs @@ -8,12 +8,12 @@ namespace FivePRS.Server.Database public sealed class CivilianStore : SqlStore { private const string CharacterColumns = - "id, owner_license, first_name, last_name, date_of_birth, gender, created_at, last_used_at"; + "id, owner_license, first_name, last_name, date_of_birth, gender, created_at, last_used_at, external_id"; private const string VehicleColumns = "id, character_id, plate, model, status, registered_at"; private const string RecordColumns = - "id, character_id, type, description, fine, officer_name, officer_callsign, created_at, active, resolution"; + "id, character_id, type, description, fine, officer_name, officer_callsign, created_at, active, resolution, fine_status"; private const string ActiveWarrantExists = "EXISTS (SELECT 1 FROM fiveprs_records r WHERE r.character_id = c.id AND r.type = 3 AND r.active = 1) AS has_warrant"; @@ -46,13 +46,31 @@ public async Task CreateCharacterAsync(CharacterInfo character) { var now = DateTime.UtcNow; var id = await InsertAsync( - "INSERT INTO fiveprs_characters (owner_license, first_name, last_name, date_of_birth, gender, created_at, last_used_at) " + - "VALUES (@owner, @first, @last, @dob, @gender, @now, @now)", + "INSERT INTO fiveprs_characters (owner_license, first_name, last_name, date_of_birth, gender, created_at, last_used_at, external_id) " + + "VALUES (@owner, @first, @last, @dob, @gender, @now, @now, @external)", ("@owner", character.OwnerLicense), ("@first", character.FirstName), ("@last", character.LastName), - ("@dob", character.DateOfBirth), ("@gender", character.Gender), ("@now", now)); + ("@dob", character.DateOfBirth), ("@gender", character.Gender), ("@now", now), ("@external", character.ExternalId)); return Convert.ToInt32(id); } + public async Task FindByExternalIdAsync(string externalId) + { + var rows = await QueryAsync($"SELECT {CharacterColumns} FROM fiveprs_characters WHERE external_id = @external", + ReadCharacter, ("@external", externalId)); + return rows.Count > 0 ? rows[0] : null; + } + + public Task UpdateLinkedCharacterAsync(CharacterInfo character) => + ExecuteAsync( + "UPDATE fiveprs_characters SET owner_license = @owner, first_name = @first, last_name = @last, date_of_birth = @dob, gender = @gender " + + "WHERE id = @id", + ("@owner", character.OwnerLicense), ("@first", character.FirstName), ("@last", character.LastName), + ("@dob", character.DateOfBirth), ("@gender", character.Gender), ("@id", character.Id)); + + public Task MoveVehicleAsync(int vehicleId, int characterId, string model) => + ExecuteAsync("UPDATE fiveprs_vehicles SET character_id = @character, model = @model WHERE id = @id", + ("@character", characterId), ("@model", model), ("@id", vehicleId)); + public Task TouchCharacterAsync(int id) => ExecuteAsync("UPDATE fiveprs_characters SET last_used_at = @now WHERE id = @id", ("@now", DateTime.UtcNow), ("@id", id)); @@ -150,14 +168,22 @@ public Task> GetRecordsAsync(int characterId) => public async Task AddRecordAsync(RecordInfo record, string officerLicense) { var id = await InsertAsync( - "INSERT INTO fiveprs_records (character_id, type, description, fine, officer_license, officer_name, officer_callsign, created_at, active) " + - "VALUES (@character, @type, @description, @fine, @officerLicense, @officerName, @callsign, @now, @active)", + "INSERT INTO fiveprs_records (character_id, type, description, fine, officer_license, officer_name, officer_callsign, created_at, active, fine_status) " + + "VALUES (@character, @type, @description, @fine, @officerLicense, @officerName, @callsign, @now, @active, @fineStatus)", ("@character", record.CharacterId), ("@type", (int)record.Type), ("@description", record.Description), ("@fine", record.Fine), ("@officerLicense", officerLicense), ("@officerName", record.OfficerName), - ("@callsign", record.OfficerCallsign), ("@now", DateTime.UtcNow), ("@active", record.Active ? 1 : 0)); + ("@callsign", record.OfficerCallsign), ("@now", DateTime.UtcNow), ("@active", record.Active ? 1 : 0), + ("@fineStatus", (int)record.FineStatus)); return Convert.ToInt32(id); } + public Task> GetUnpaidFinesAsync(int characterId) => + QueryAsync($"SELECT {RecordColumns} FROM fiveprs_records WHERE character_id = @id AND fine_status = @unpaid ORDER BY created_at, id", + ReadRecord, ("@id", characterId), ("@unpaid", (int)FineStatus.Unpaid)); + + public Task SetFineStatusAsync(int recordId, FineStatus status) => + ExecuteAsync("UPDATE fiveprs_records SET fine_status = @status WHERE id = @id", ("@status", (int)status), ("@id", recordId)); + public Task ResolveRecordAsync(int id, string resolution) => ExecuteAsync("UPDATE fiveprs_records SET active = 0, resolution = @resolution WHERE id = @id", ("@resolution", resolution), ("@id", id)); @@ -184,6 +210,7 @@ public Task ResolveRecordAsync(int id, string resolution) => CreatedAt = row.GetDateTime("created_at"), Active = row.GetBoolean("active"), Resolution = row.IsNull("resolution") ? null : row.GetString("resolution"), + FineStatus = (FineStatus)row.GetInt32("fine_status"), }; private static CharacterInfo ReadCharacter(DbRow row) => new() @@ -196,6 +223,7 @@ public Task ResolveRecordAsync(int id, string resolution) => Gender = row.GetString("gender"), CreatedAt = row.GetDateTime("created_at"), LastUsedAt = row.GetDateTime("last_used_at"), + ExternalId = row.IsNull("external_id") ? null : row.GetString("external_id"), }; private static VehicleInfo ReadVehicle(DbRow row) => new() diff --git a/FivePRS.Server/Database/DatabaseManager.cs b/FivePRS.Server/Database/DatabaseManager.cs index 9f30f76..7521793 100644 --- a/FivePRS.Server/Database/DatabaseManager.cs +++ b/FivePRS.Server/Database/DatabaseManager.cs @@ -32,6 +32,7 @@ public sealed class DatabaseManager public PhotoStore Photos { get; private set; } = null!; public ReportStore Reports { get; private set; } = null!; + public SpeedClockStore SpeedClocks { get; private set; } = null!; public PositionStore Positions { get; private set; } = null!; @@ -93,6 +94,7 @@ private async Task InitializeCoreAsync(DatabaseType dbType, string? connectionSt Preferences = new PreferencesStore(_provider); Photos = new PhotoStore(_provider); Reports = new ReportStore(_provider); + SpeedClocks = new SpeedClockStore(_provider); Positions = new PositionStore(_provider); IsReady = true; diff --git a/FivePRS.Server/Database/Migrations.cs b/FivePRS.Server/Database/Migrations.cs index bfdffd6..89ed390 100644 --- a/FivePRS.Server/Database/Migrations.cs +++ b/FivePRS.Server/Database/Migrations.cs @@ -244,6 +244,43 @@ PRIMARY KEY (`id`), KEY `idx_fiveprs_reports_status` (`status`, `created_at`), KEY `idx_fiveprs_reports_character` (`character_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci")), + new Migration(4, "Framework characters", + new AddColumnStep("fiveprs_characters", "external_id", "TEXT NULL", "VARCHAR(80) NULL"), + Sql("CREATE UNIQUE INDEX IF NOT EXISTS idx_fiveprs_characters_external ON fiveprs_characters(external_id)", + "CREATE UNIQUE INDEX `idx_fiveprs_characters_external` ON `fiveprs_characters` (`external_id`)")), + new Migration(5, "Fine payments", + new AddColumnStep("fiveprs_records", "fine_status", "INTEGER NOT NULL DEFAULT 0", "TINYINT UNSIGNED NOT NULL DEFAULT 0")), + new Migration(6, "Speed clocks", + Sql(@"CREATE TABLE IF NOT EXISTS fiveprs_speed_clocks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + officer_license TEXT NOT NULL, + officer_name TEXT NOT NULL, + source INTEGER NOT NULL, + speed INTEGER NOT NULL, + fast INTEGER NULL, + units TEXT NOT NULL, + distance INTEGER NULL, + plate TEXT NULL, + model TEXT NULL, + location TEXT NOT NULL, + created_at TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS idx_fiveprs_speed_clocks_officer ON fiveprs_speed_clocks(officer_license, created_at)", + @"CREATE TABLE IF NOT EXISTS `fiveprs_speed_clocks` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `officer_license` VARCHAR(60) NOT NULL, + `officer_name` VARCHAR(100) NOT NULL, + `source` TINYINT UNSIGNED NOT NULL, + `speed` SMALLINT UNSIGNED NOT NULL, + `fast` SMALLINT UNSIGNED NULL, + `units` VARCHAR(4) NOT NULL, + `distance` SMALLINT UNSIGNED NULL, + `plate` VARCHAR(8) NULL, + `model` VARCHAR(40) NULL, + `location` VARCHAR(80) NOT NULL, + `created_at` DATETIME(6) NOT NULL, + PRIMARY KEY (`id`), + KEY `idx_fiveprs_speed_clocks_officer` (`officer_license`, `created_at`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci")), }; private static SqlStep Sql(string sqlite, string mySql) => new SqlStep(sqlite, mySql); diff --git a/FivePRS.Server/Database/SpeedClockStore.cs b/FivePRS.Server/Database/SpeedClockStore.cs new file mode 100644 index 0000000..ad56e04 --- /dev/null +++ b/FivePRS.Server/Database/SpeedClockStore.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using FivePRS.Core.Civilian; +using FivePRS.Core.Police; + +namespace FivePRS.Server.Database +{ + public sealed class SpeedClockStore : SqlStore + { + private const string Columns = "id, source, speed, fast, units, distance, plate, model, location, created_at"; + + public SpeedClockStore(IDatabaseProvider db) : base(db) + { + } + + public async Task AddAsync(SpeedClock clock, OfficerInfo officer) + { + var id = await InsertAsync( + "INSERT INTO fiveprs_speed_clocks (officer_license, officer_name, source, speed, fast, units, distance, plate, model, location, created_at) " + + "VALUES (@license, @name, @source, @speed, @fast, @units, @distance, @plate, @model, @location, @now)", + ("@license", officer.License), ("@name", officer.Name), ("@source", (int)clock.Source), ("@speed", clock.Speed), + ("@fast", clock.Fast), ("@units", clock.Units), ("@distance", clock.Distance), ("@plate", clock.Plate), + ("@model", clock.Model), ("@location", clock.Location), ("@now", DateTime.UtcNow)); + return Convert.ToInt32(id); + } + + public Task> RecentAsync(string license, int limit) => + QueryAsync($"SELECT {Columns} FROM fiveprs_speed_clocks WHERE officer_license = @license ORDER BY created_at DESC, id DESC LIMIT {limit}", + Read, ("@license", license)); + + public Task PruneAsync(DateTime before) => + ExecuteAsync("DELETE FROM fiveprs_speed_clocks WHERE created_at < @before", ("@before", before)); + + private static SpeedClock Read(DbRow row) => new() + { + Id = row.GetInt32("id"), + Source = (SpeedClockSource)row.GetInt32("source"), + Speed = row.GetInt32("speed"), + Fast = row.IsNull("fast") ? null : row.GetInt32("fast"), + Units = row.GetString("units"), + Distance = row.IsNull("distance") ? null : row.GetInt32("distance"), + Plate = row.IsNull("plate") ? null : row.GetString("plate"), + Model = row.IsNull("model") ? null : row.GetString("model"), + Location = row.GetString("location"), + CreatedAt = row.GetDateTime("created_at"), + }; + } +} diff --git a/FivePRS.Server/Framework/CharacterLinker.cs b/FivePRS.Server/Framework/CharacterLinker.cs new file mode 100644 index 0000000..303e3af --- /dev/null +++ b/FivePRS.Server/Framework/CharacterLinker.cs @@ -0,0 +1,117 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading.Tasks; +using FivePRS.Core.Civilian; +using FivePRS.Server.Database; + +namespace FivePRS.Server.Framework +{ + public sealed class ExternalIdentity + { + public string ExternalId { get; set; } = string.Empty; + public string? OwnerLicense { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } + public string? DateOfBirth { get; set; } + public string? Gender { get; set; } + } + + public sealed class ExternalVehicle + { + public string Plate { get; set; } = string.Empty; + public string? Model { get; set; } + } + + public sealed class CharacterLinker + { + public const string UnknownName = "Unknown"; + public const string UnknownModel = "Unknown"; + public const string PlaceholderOwner = "framework:"; + + private const int MaxModelLength = 40; + + private readonly CivilianStore _store; + + public CharacterLinker(CivilianStore store) => _store = store; + + public async Task LinkAsync(ExternalIdentity identity) + { + var existing = await _store.FindByExternalIdAsync(identity.ExternalId); + var owner = string.IsNullOrWhiteSpace(identity.OwnerLicense) + ? existing?.OwnerLicense ?? PlaceholderOwner + identity.ExternalId + : identity.OwnerLicense!; + + var character = new CharacterInfo + { + OwnerLicense = owner, + FirstName = CleanName(identity.FirstName), + LastName = CleanName(identity.LastName), + DateOfBirth = CleanDate(identity.DateOfBirth), + Gender = CivilianRules.TryNormalizeGender(identity.Gender, out var gender) ? gender : "Male", + ExternalId = identity.ExternalId, + }; + + if (existing is null) + return await _store.CreateCharacterAsync(character); + + character.Id = existing.Id; + if (existing.OwnerLicense != character.OwnerLicense || existing.FirstName != character.FirstName || + existing.LastName != character.LastName || existing.DateOfBirth != character.DateOfBirth || existing.Gender != character.Gender) + { + await _store.UpdateLinkedCharacterAsync(character); + } + + return existing.Id; + } + + public async Task LinkVehicleAsync(int characterId, ExternalVehicle vehicle) + { + if (!CivilianRules.TryNormalizePlate(vehicle.Plate, out var plate)) return false; + + var model = CleanModel(vehicle.Model); + var existing = await _store.GetVehicleByPlateAsync(plate); + if (existing is null) + { + await _store.AddVehicleAsync(new VehicleInfo { CharacterId = characterId, Plate = plate, Model = model, Status = VehicleStatus.Valid }); + return true; + } + + if (existing.CharacterId != characterId || existing.Model != model) + await _store.MoveVehicleAsync(existing.Id, characterId, model); + return true; + } + + public async Task SyncVehiclesAsync(int characterId, IEnumerable vehicles) + { + var owned = new HashSet(); + foreach (var vehicle in vehicles) + { + if (await LinkVehicleAsync(characterId, vehicle) && CivilianRules.TryNormalizePlate(vehicle.Plate, out var plate)) + owned.Add(plate); + } + + foreach (var stale in (await _store.GetVehiclesAsync(characterId)).Where(v => !owned.Contains(v.Plate))) + await _store.DeleteVehicleAsync(stale.Id); + } + + private static string CleanName(string? name) + { + var text = (name ?? string.Empty).Trim(); + if (text.Length == 0) return UnknownName; + return text.Length > CivilianRules.MaxNameLength ? text.Substring(0, CivilianRules.MaxNameLength).TrimEnd() : text; + } + + private static string CleanDate(string? date) => + System.DateTime.TryParseExact((date ?? string.Empty).Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed) + ? parsed.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + : string.Empty; + + private static string CleanModel(string? model) + { + var text = (model ?? string.Empty).Trim(); + if (text.Length == 0) return UnknownModel; + return text.Length > MaxModelLength ? text.Substring(0, MaxModelLength) : text; + } + } +} diff --git a/FivePRS.Server/Framework/FrameworkBridge.cs b/FivePRS.Server/Framework/FrameworkBridge.cs new file mode 100644 index 0000000..df87220 --- /dev/null +++ b/FivePRS.Server/Framework/FrameworkBridge.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; +using CitizenFX.Core; +using FivePRS.Core.Events; +using Newtonsoft.Json; + +namespace FivePRS.Server.Framework +{ + public sealed class FrameworkCharacter + { + public string Id { get; set; } = string.Empty; + public string? FirstName { get; set; } + public string? LastName { get; set; } + public string? DateOfBirth { get; set; } + public string Gender { get; set; } = "Male"; + public string? Job { get; set; } + public int Grade { get; set; } + public string? GradeName { get; set; } + public bool? OnDuty { get; set; } + public bool TracksDuty { get; set; } + + public string FullName => $"{FirstName} {LastName}".Trim(); + } + + public sealed class FrameworkOwner + { + public string Id { get; set; } = string.Empty; + public string? License { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } + public string? DateOfBirth { get; set; } + public string? Gender { get; set; } + } + + public sealed class FrameworkVehicle + { + public string Plate { get; set; } = string.Empty; + public string? Model { get; set; } + public FrameworkOwner? Owner { get; set; } + } + + public sealed class FrameworkInfo + { + public string Name { get; set; } = string.Empty; + public string Family { get; set; } = string.Empty; + public string Resource { get; set; } = string.Empty; + } + + public sealed class FrameworkBridge + { + private const int TimeoutMs = 45_000; + + private static readonly ConcurrentDictionary> Pending = new(); + + public FrameworkBridge(FrameworkInfo info) => Info = info; + + public FrameworkInfo Info { get; } + + public static string DisplayName(string name) => name switch + { + "qbox" => "Qbox", + "qbcore" => "QBCore", + "esx" => "ESX Legacy", + "ox" => "ox_core", + "nd" => "ND_Core", + _ => name, + }; + + public static async Task DetectAsync(string preferred) + { + var info = await RequestAsync("detect", new { preferred }); + return info is null || string.IsNullOrEmpty(info.Name) ? null : new FrameworkBridge(info); + } + + public Task CharacterAsync(int source, IEnumerable jobs) => + RequestAsync("character", new { source, jobs }); + + public string ExternalId(string id) => $"{Info.Family}:{id}"; + + public async Task> VehiclesAsync(string characterId) + { + var json = await RawAsync("vehicles", new { id = characterId }); + return json.TrimStart().StartsWith("[") + ? JsonConvert.DeserializeObject>(json) ?? new List() + : new List(); + } + + public Task VehicleAsync(string plate) => + RequestAsync("vehicle", new { plate = plate.Replace(" ", string.Empty) }); + + public Task SetDutyAsync(int source, bool onDuty) => + RequestAsync("setDuty", new { source, onDuty }); + + public Task RemoveMoneyAsync(int source, string account, int amount, string reason) => + RequestAsync("removeMoney", new { source, account, amount, reason }); + + private static async Task RequestAsync(string method, object args) + { + var json = await RawAsync(method, args); + return string.IsNullOrEmpty(json) ? default! : JsonConvert.DeserializeObject(json)!; + } + + private static async Task RawAsync(string method, object args) + { + await MainThread.Resume(); + + var id = Guid.NewGuid().ToString("N"); + var completion = new TaskCompletionSource(); + Pending[id] = completion; + + try + { + BaseScript.TriggerEvent(EventNames.LocalFrameworkRequest, id, method, JsonConvert.SerializeObject(args)); + + var finished = await Task.WhenAny(completion.Task, BaseScript.Delay(TimeoutMs)); + await MainThread.Resume(); + if (finished != completion.Task) + throw new TimeoutException($"The framework didn't answer '{method}' within {TimeoutMs / 1000} seconds."); + + return await completion.Task; + } + finally + { + Pending.TryRemove(id, out _); + } + } + + public static void OnResponse(string id, string result, string error) + { + if (id is null || !Pending.TryGetValue(id, out var completion)) return; + + if (string.IsNullOrEmpty(error)) + completion.TrySetResult(result ?? string.Empty); + else + completion.TrySetException(new InvalidOperationException(error)); + } + } +} diff --git a/FivePRS.Server/ServerBrain.Admin.cs b/FivePRS.Server/ServerBrain.Admin.cs index fbae702..95ea15e 100644 --- a/FivePRS.Server/ServerBrain.Admin.cs +++ b/FivePRS.Server/ServerBrain.Admin.cs @@ -8,6 +8,7 @@ using FivePRS.Core.Events; using FivePRS.Core.Logging; using FivePRS.Core.Models; +using FivePRS.Server.Framework; using FivePRS.Server.Database; namespace FivePRS.Server @@ -60,10 +61,11 @@ private void RegisterAdminCommand(string name, string usage, int requiredArgs, F private async Task SetRankAsync(Player? caller, string[] args) { + if (UsesFramework) return FrameworkOwnsJobs("rank", "grade"); if (!TryGetTarget(args[0], out var target, out var data)) return TargetNotFound(args[0]); var ladder = data.Ladder(); if (!int.TryParse(args[1], out var rank) || rank < 1 || rank > ladder.Count) - return CommandResult.Failed($"Rank must be a number from 1 to {ladder.Count} for {data.Department}."); + return CommandResult.Failed($"Rank must be a number from 1 to {ladder.Count} for {ConfigManager.DisplayName(data.Department)}."); data.Rank = rank; data.XP = 0; @@ -78,8 +80,15 @@ private async Task SetRankAsync(Player? caller, string[] args) return CommandResult.Done($"{data.Name} is now {name} (rank {rank})."); } + private CommandResult FrameworkOwnsJobs(string what, string frameworkTerm) => CommandResult.Failed( + $"{FrameworkBridge.DisplayName(_framework!.Info.Name)} decides the {what}. Change the character's {frameworkTerm} there, or the mapping in config/framework.json."); + private async Task AddXpAsync(Player? caller, string[] args) { + if (!XpActive) + return CommandResult.Failed(UsesFramework + ? $"XP is off while {FrameworkBridge.DisplayName(_framework!.Info.Name)} decides ranks." + : "XP is turned off. Set xpEnabled to true in config/settings.json to use it."); if (!TryGetTarget(args[0], out var target, out var data)) return TargetNotFound(args[0]); if (!int.TryParse(args[1], out var amount) || amount < 1 || amount > MaxXpGrant) return CommandResult.Failed($"Amount must be a number from 1 to {MaxXpGrant:N0}."); @@ -93,20 +102,19 @@ private async Task AddXpAsync(Player? caller, string[] args) private async Task SetDepartmentAsync(Player? caller, string[] args) { + if (UsesFramework) return FrameworkOwnsJobs("department", "job"); if (!TryGetTarget(args[0], out var target, out var data)) return TargetNotFound(args[0]); - var department = Enum.GetValues(typeof(Department)).Cast() - .FirstOrDefault(d => d != Department.None && string.Equals(d.ToString(), args[1], StringComparison.OrdinalIgnoreCase)); - if (department == Department.None) + if (!ConfigManager.TryParseDepartment(args[1], out var department)) { - var names = Enum.GetValues(typeof(Department)).Cast().Where(d => d != Department.None); + var names = ConfigManager.Departments.Select(ConfigManager.ConfigName); return CommandResult.Failed($"Unknown department '{args[1]}'. Use {string.Join(", ", names)}."); } await ChangeDepartmentAsync(target, data, department); - Notify(target, $"~y~Your department was set to {department} by an administrator."); + Notify(target, $"~y~Your department was set to {ConfigManager.DisplayName(department)} by an administrator."); Audit(AuditActions.AdminSetDept, caller, data.License, department.ToString()); - return CommandResult.Done($"{data.Name} is now in {department}."); + return CommandResult.Done($"{data.Name} is now in {ConfigManager.DisplayName(department)}."); } private async Task ForceOffDutyAsync(Player? caller, string[] args) diff --git a/FivePRS.Server/ServerBrain.Appearance.cs b/FivePRS.Server/ServerBrain.Appearance.cs index a94fcc6..64222ff 100644 --- a/FivePRS.Server/ServerBrain.Appearance.cs +++ b/FivePRS.Server/ServerBrain.Appearance.cs @@ -18,6 +18,8 @@ private void RegisterAppearanceEvents() private void OnAppearanceSave([FromSource] Player player, int characterId, string json) => RunCivilian(player, (_, license) => _appearances is null ? Task.FromResult("Appearances are not available yet.") + : UsesFramework + ? Task.FromResult("Change your look with your server's clothing script.") : _appearances.SaveAsync(license, characterId, json)); private async Task SendAppearanceAsync(Player player, string license) @@ -25,7 +27,7 @@ private async Task SendAppearanceAsync(Player player, string license) if (_civilians is null || _appearances is null) return; var active = await _civilians.GetActiveCharacterAsync(license); - var json = active is null ? null : await _appearances.GetAsync(active.Id); + var json = active is null || UsesFramework ? null : await _appearances.GetAsync(active.Id); TriggerClientEvent(player, EventNames.ClientAppearance, active?.Id ?? 0, json ?? string.Empty); } } diff --git a/FivePRS.Server/ServerBrain.Death.cs b/FivePRS.Server/ServerBrain.Death.cs index 4fa4173..d712093 100644 --- a/FivePRS.Server/ServerBrain.Death.cs +++ b/FivePRS.Server/ServerBrain.Death.cs @@ -68,7 +68,7 @@ private async void OnRevivePlayer([FromSource] Player medic, int targetId) Audit(AuditActions.PlayerRevived, medic, GetLicense(target), $"revived {target.Name}"); var xp = ConfigManager.Settings.Death.ReviveXp; - if (isMedic && xp > 0) + if (isMedic && xp > 0 && XpActive) { try { diff --git a/FivePRS.Server/ServerBrain.Diagnostics.cs b/FivePRS.Server/ServerBrain.Diagnostics.cs index 0ccda0a..8bf81be 100644 --- a/FivePRS.Server/ServerBrain.Diagnostics.cs +++ b/FivePRS.Server/ServerBrain.Diagnostics.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading.Tasks; using CitizenFX.Core; +using FivePRS.Server.Framework; using CitizenFX.Core.Native; using FivePRS.Core.Config; using FivePRS.Core.Models; @@ -78,6 +79,7 @@ private List DiagnosticFacts() new("Platform", $"{Platform()}, runtime {Environment.Version}"), new("OneSync", API.GetConvar("onesync", "off")), new("Database", _db.IsReady ? $"{_databaseType}, schema {_db.SchemaVersion}" : "not ready"), + new("Framework", _framework is null ? "standalone" : $"{FrameworkBridge.DisplayName(_framework.Info.Name)} ({_framework.Info.Resource})"), new("Players", $"{players} online, {units} on duty"), new("Dispatch", $"{_dispatch.CatalogCount} callouts, {_dispatch.ActiveCallCount} active calls"), new("Rate limits", ConfigManager.Settings.RateLimits.Enabled ? "on" : "off"), diff --git a/FivePRS.Server/ServerBrain.Emergency.cs b/FivePRS.Server/ServerBrain.Emergency.cs index 0b1f0b6..9b3f23b 100644 --- a/FivePRS.Server/ServerBrain.Emergency.cs +++ b/FivePRS.Server/ServerBrain.Emergency.cs @@ -2,6 +2,7 @@ using CitizenFX.Core; using CitizenFX.Core.Native; using FivePRS.Core.Civilian; +using FivePRS.Core.Config; using FivePRS.Core.Events; using FivePRS.Core.Models; using FivePRS.Server.Database; @@ -71,7 +72,7 @@ private async void OnEmergencyCall([FromSource] Player player, int departmentId, Notify(unit, $"~r~911 Call #{callId}~w~ | {callerName}: {text}"); } - SendEmergencyStatus(ServerId(player), $"~b~911~w~ | Your call #{callId} has been sent to {department}."); + SendEmergencyStatus(ServerId(player), $"~b~911~w~ | Your call #{callId} has been sent to {ConfigManager.DisplayName(department)}."); } catch (Exception ex) { diff --git a/FivePRS.Server/ServerBrain.Framework.cs b/FivePRS.Server/ServerBrain.Framework.cs new file mode 100644 index 0000000..07381ac --- /dev/null +++ b/FivePRS.Server/ServerBrain.Framework.cs @@ -0,0 +1,298 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading.Tasks; +using CitizenFX.Core; +using FivePRS.Core.Civilian; +using FivePRS.Core.Config; +using FivePRS.Core.Events; +using FivePRS.Core.Models; +using FivePRS.Server.Framework; +using Newtonsoft.Json; + +namespace FivePRS.Server +{ + public partial class ServerBrain + { + private const string TerminalKey = "F5"; + + private FrameworkBridge? _framework; + private CharacterLinker? _linker; + private readonly ConcurrentDictionary _frameworkCharacters = new(); + private readonly ConcurrentDictionary _frameworkJobs = new(); + + private bool UsesFramework => _framework is not null; + + private void RegisterFrameworkEvents() + { + EventHandlers[EventNames.LocalFrameworkResponse] += new Action(FrameworkBridge.OnResponse); + EventHandlers[EventNames.LocalFrameworkChanged] += new Action(OnFrameworkChanged); + } + + private async Task DetectFrameworkAsync() + { + var preferred = ConfigManager.Framework.Preferred; + if (preferred != FrameworkConfig.Auto && preferred != FrameworkConfig.Standalone && !FrameworkConfig.Supported.Contains(preferred)) + { + Log.Warn($"framework.json names an unknown framework \"{preferred}\". Use auto, standalone, {string.Join(", ", FrameworkConfig.Supported)}."); + return; + } + + try + { + _framework = await FrameworkBridge.DetectAsync(preferred); + } + catch (Exception ex) + { + Log.Error("Could not check for a framework, running standalone", ex); + return; + } + + if (_framework is null) + { + if (preferred != FrameworkConfig.Auto && preferred != FrameworkConfig.Standalone) + Log.Warn($"framework.json asks for {FrameworkBridge.DisplayName(preferred)}, but it isn't running. Running standalone."); + return; + } + + var name = FrameworkBridge.DisplayName(_framework.Info.Name); + _linker = new CharacterLinker(_db.Civilians); + if (_civilians is not null) _civilians.ManagedBy = name; + if (_lookup is not null) + { + _lookup.ExternalPlate = LinkFrameworkPlateAsync; + _lookup.CollectsFines = ConfigManager.Framework.Fines.Collect; + } + + Log.Success($"Using {name} ({_framework.Info.Resource}) for jobs, duty, characters and vehicles."); + foreach (var player in Players.ToList()) + await SyncFrameworkAsync(player); + } + + private async void OnFrameworkChanged(int source, string kind) + { + if (_framework is null || source <= 0 || !TryGetPlayer(source, out var player)) return; + + if (kind == "unloaded") + { + await ClearFrameworkCharacterAsync(player, "~o~You logged out of your character.~w~ Your shift has ended."); + return; + } + + await SyncFrameworkAsync(player); + } + + private async Task SyncFrameworkAsync(Player player) + { + if (_framework is null || !TryGetCached(player, out var license, out var data)) return; + var source = ServerId(player); + + FrameworkCharacter? character; + try + { + character = await _framework.CharacterAsync(source, ConfigManager.Framework.Jobs.Keys); + } + catch (Exception ex) + { + Log.Warn($"Could not read {player.Name}'s character from {FrameworkBridge.DisplayName(_framework.Info.Name)}", ex); + return; + } + + if (character is null || string.IsNullOrEmpty(character.Id)) + { + await ClearFrameworkCharacterAsync(player, null); + return; + } + + _frameworkCharacters.TryGetValue(source, out var previous); + _frameworkCharacters[source] = character; + + if (character.FullName.Length > 0) data.Name = character.FullName; + await LinkFrameworkCharacterAsync(player, license, character); + + var match = ConfigManager.Framework.Resolve(character.Job, character.Grade, department => ConfigManager.RanksFor(department).Count); + if (match is null) + { + _frameworkJobs.TryRemove(source, out _); + if (data.IsOnDuty) await EndFrameworkShiftAsync(player, data, "~o~Your job changed.~w~ Your FivePRS shift has ended."); + } + else + { + _frameworkJobs[source] = match; + if (data.IsOnDuty && data.Department != match.Department) + await EndFrameworkShiftAsync(player, data, "~o~Your job changed.~w~ Your FivePRS shift has ended."); + + data.Department = match.Department; + data.Agency = ConfigManager.Territories.ResolveAgency(match.Department, match.Agency ?? data.Agency)?.Id ?? string.Empty; + if (data.Rank != match.Rank) + { + data.Rank = match.Rank; + if (data.IsOnDuty) _dispatch.UpdateRank(source, data.Rank); + } + + if (character.TracksDuty && data.IsOnDuty && character.OnDuty == false) + await EndFrameworkShiftAsync(player, data, "~o~You clocked out.~w~ Your FivePRS shift has ended."); + else if (character.TracksDuty && !data.IsOnDuty && character.OnDuty == true && previous?.OnDuty != true) + Notify(player, $"~b~FivePRS~w~ | You're clocked in. Open the terminal ({TerminalKey}) and start your shift from the Duty app."); + } + + await _db.SavePlayerAsync(data); + SendPlayerData(player, data); + SendEntryOptions(player); + } + + private async Task ClearFrameworkCharacterAsync(Player player, string? message) + { + var source = ServerId(player); + _frameworkCharacters.TryRemove(source, out _); + _frameworkJobs.TryRemove(source, out _); + + if (TryGetCached(player, out _, out var data) && data.IsOnDuty) + await EndFrameworkShiftAsync(player, data, message); + SendEntryOptions(player); + } + + private async Task EndFrameworkShiftAsync(Player player, PlayerData data, string? message) + { + await SetDutyAsync(player, data, false); + if (message is not null) Notify(player, message); + } + + private async Task LinkFrameworkCharacterAsync(Player player, string license, FrameworkCharacter character) + { + if (_framework is null || _linker is null) return; + + try + { + var characterId = await _linker.LinkAsync(new ExternalIdentity + { + ExternalId = _framework.ExternalId(character.Id), + OwnerLicense = license, + FirstName = character.FirstName, + LastName = character.LastName, + DateOfBirth = character.DateOfBirth, + Gender = character.Gender, + }); + await _db.Civilians.TouchCharacterAsync(characterId); + + var vehicles = await _framework.VehiclesAsync(character.Id); + await _linker.SyncVehiclesAsync(characterId, vehicles.Select(v => new ExternalVehicle { Plate = v.Plate, Model = v.Model })); + await CollectFinesAsync(characterId); + + if (_civilians is not null) + { + var state = await _civilians.GetStateAsync(license); + TriggerClientEvent(player, EventNames.ClientCivilianState, JsonConvert.SerializeObject(state)); + } + } + catch (Exception ex) + { + Log.Warn($"Could not link {player.Name}'s character", ex); + } + } + + private async Task CollectFinesAsync(int characterId) + { + if (_framework is null || !ConfigManager.Framework.Fines.Collect) return; + + try + { + var character = await _db.Civilians.GetCharacterAsync(characterId); + if (character?.ExternalId is null) return; + + var source = _frameworkCharacters.FirstOrDefault(entry => _framework.ExternalId(entry.Value.Id) == character.ExternalId).Key; + if (source <= 0 || !TryGetPlayer(source, out var player)) return; + + var paid = 0; + var unpaid = 0; + foreach (var record in await _db.Civilians.GetUnpaidFinesAsync(characterId)) + { + if (unpaid == 0 && await _framework.RemoveMoneyAsync(source, ConfigManager.Framework.Fines.Account, record.Fine, $"Citation: {record.Description}")) + { + await _db.Civilians.SetFineStatusAsync(record.Id, FineStatus.Paid); + paid += record.Fine; + } + else + { + unpaid += record.Fine; + } + } + + if (paid > 0) Notify(player, $"~y~Fines~w~ | ${paid:N0} was taken from your {ConfigManager.Framework.Fines.Account} for citations."); + if (unpaid > 0) Notify(player, $"~o~Fines~w~ | You couldn't pay ${unpaid:N0} in fines. It will be collected later."); + } + catch (Exception ex) + { + Log.Warn($"Could not collect fines for character {characterId}", ex); + } + } + + private async Task LinkFrameworkPlateAsync(string plate) + { + if (_framework is null || _linker is null) return false; + + try + { + var vehicle = await _framework.VehicleAsync(plate); + if (vehicle?.Owner is null || string.IsNullOrEmpty(vehicle.Owner.Id)) return false; + + var characterId = await _linker.LinkAsync(new ExternalIdentity + { + ExternalId = _framework.ExternalId(vehicle.Owner.Id), + OwnerLicense = vehicle.Owner.License, + FirstName = vehicle.Owner.FirstName, + LastName = vehicle.Owner.LastName, + DateOfBirth = vehicle.Owner.DateOfBirth, + Gender = vehicle.Owner.Gender, + }); + return await _linker.LinkVehicleAsync(characterId, new ExternalVehicle { Plate = vehicle.Plate, Model = vehicle.Model }); + } + catch (Exception ex) + { + Log.Warn($"Could not look up plate {plate} in {FrameworkBridge.DisplayName(_framework.Info.Name)}", ex); + return false; + } + } + + private bool CanJoin(Player player, Department department) + { + if (_framework is null) return _permissions.CanJoinDepartment(player.Handle, department); + if (department == Department.None) return false; + if (_permissions.IsAdmin(player.Handle)) return true; + return _frameworkJobs.TryGetValue(ServerId(player), out var match) && match.Department == department; + } + + private string? FrameworkAgency(Player player, Department department) => + _frameworkJobs.TryGetValue(ServerId(player), out var match) && match.Department == department ? match.Agency : null; + + private void SyncFrameworkDuty(Player player, bool onDuty) + { + if (_framework is null) return; + if (_frameworkCharacters.TryGetValue(ServerId(player), out var character)) + { + if (!character.TracksDuty || character.OnDuty == onDuty) return; + character.OnDuty = onDuty; + } + + _ = PushFrameworkDutyAsync(_framework, ServerId(player), onDuty); + } + + private static async Task PushFrameworkDutyAsync(FrameworkBridge framework, int source, bool onDuty) + { + try + { + await framework.SetDutyAsync(source, onDuty); + } + catch (Exception ex) + { + Log.Warn($"Could not update duty in {FrameworkBridge.DisplayName(framework.Info.Name)}", ex); + } + } + + private void ForgetFrameworkCharacter(Player player) + { + _frameworkCharacters.TryRemove(ServerId(player), out _); + _frameworkJobs.TryRemove(ServerId(player), out _); + } + } +} diff --git a/FivePRS.Server/ServerBrain.Lookup.cs b/FivePRS.Server/ServerBrain.Lookup.cs index 427c21e..722218d 100644 --- a/FivePRS.Server/ServerBrain.Lookup.cs +++ b/FivePRS.Server/ServerBrain.Lookup.cs @@ -54,6 +54,7 @@ private void OnRecordIssue([FromSource] Player player, int characterId, int type } Audit(AuditActions.RecordIssued, player, await OwnerLicenseAsync(characterId), $"{label} character {characterId}"); + if (type == (int)RecordType.Citation && fine > 0) await CollectFinesAsync(characterId); await NotifyCharacterOwnerAsync(characterId, $"~o~Records update~w~ | A {label} was added to your record by {officer.Callsign}."); return await lookup.GetRecordAsync(characterId); }); diff --git a/FivePRS.Server/ServerBrain.Positions.cs b/FivePRS.Server/ServerBrain.Positions.cs index 6d722ee..bee3ceb 100644 --- a/FivePRS.Server/ServerBrain.Positions.cs +++ b/FivePRS.Server/ServerBrain.Positions.cs @@ -27,7 +27,7 @@ private void RegisterPositionEvents() private void OnReportPosition([FromSource] Player player, float x, float y, float z, float heading) { - if (!Allow(player, "positions", l => l.Positions)) return; + if (!Allow(player, "positions", l => l.Positions) || UsesFramework) return; var license = GetLicense(player); var position = SavedPosition.Create(x, y, z, heading); @@ -47,7 +47,7 @@ private async void OnLastPositionRequest([FromSource] Player player) SavedPosition? position = null; try { - if (ConfigManager.Settings.Spawn.RestoreLastLocation && _db.IsReady) + if (ConfigManager.Settings.Spawn.RestoreLastLocation && _db.IsReady && !UsesFramework) position = _positions.TryGetValue(license, out var cached) ? cached : await _db.Positions.GetAsync(license); } catch (Exception ex) @@ -58,7 +58,7 @@ private async void OnLastPositionRequest([FromSource] Player player) var model = string.Empty; try { - model = await SpawnModelAsync(license); + if (!UsesFramework) model = await SpawnModelAsync(license); } catch (Exception ex) { diff --git a/FivePRS.Server/ServerBrain.Radar.cs b/FivePRS.Server/ServerBrain.Radar.cs new file mode 100644 index 0000000..60c58bc --- /dev/null +++ b/FivePRS.Server/ServerBrain.Radar.cs @@ -0,0 +1,75 @@ +using System; +using System.Threading.Tasks; +using CitizenFX.Core; +using FivePRS.Core.Config; +using FivePRS.Core.Events; +using FivePRS.Core.Police; +using Newtonsoft.Json; + +namespace FivePRS.Server +{ + public partial class ServerBrain + { + private const int ClockHistoryLimit = 50; + + private void RegisterRadarEvents() + { + EventHandlers[EventNames.ServerSpeedClock] += new Action(OnSpeedClock); + EventHandlers[EventNames.ServerSpeedClocksRequest] += new Action(OnSpeedClocksRequest); + } + + private async void OnSpeedClock([FromSource] Player player, string json) + { + if (!ConfigManager.Settings.Radar.Enabled || !_db.IsReady) return; + if (!Allow(player, "speedClocks", l => l.SpeedClocks) || !TryGetOfficer(player, out var officer)) return; + + SpeedClock? clock; + try + { + clock = JsonConvert.DeserializeObject(json); + } + catch (JsonException) + { + return; + } + + if (clock is null || !clock.Normalize()) return; + + try + { + await _db.SpeedClocks.AddAsync(clock, officer); + } + catch (Exception ex) + { + Log.Warn($"Could not save a speed clock for {player.Name}", ex); + } + } + + private async void OnSpeedClocksRequest([FromSource] Player player) + { + if (!_db.IsReady || !Allow(player, "requests", l => l.Requests) || !TryGetOfficer(player, out var officer)) return; + + try + { + var clocks = await _db.SpeedClocks.RecentAsync(officer.License, ClockHistoryLimit); + TriggerClientEvent(player, EventNames.ClientSpeedClocks, JsonConvert.SerializeObject(clocks)); + } + catch (Exception ex) + { + Log.Warn($"Could not load speed clocks for {player.Name}", ex); + } + } + + private async Task PruneSpeedClocksAsync() + { + try + { + await _db.SpeedClocks.PruneAsync(DateTime.UtcNow.AddDays(-SpeedClock.KeepDays)); + } + catch (Exception ex) + { + Log.Warn("Could not remove old speed clocks", ex); + } + } + } +} diff --git a/FivePRS.Server/ServerBrain.Roster.cs b/FivePRS.Server/ServerBrain.Roster.cs index 81f2820..a8d0bc5 100644 --- a/FivePRS.Server/ServerBrain.Roster.cs +++ b/FivePRS.Server/ServerBrain.Roster.cs @@ -128,11 +128,11 @@ private async Task ApplyRosterChangeAsync(string license, Department department, if (granted) { - Notify(target, $"~g~Roster~w~ | You can now join {department}."); + Notify(target, $"~g~Roster~w~ | You can now join {ConfigManager.DisplayName(department)}."); return; } - Notify(target, $"~o~Roster~w~ | You were removed from {department}."); + Notify(target, $"~o~Roster~w~ | You were removed from {ConfigManager.DisplayName(department)}."); if (TryGetCached(target, out _, out var data) && data.IsOnDuty && data.Department == department && !_permissions.CanJoinDepartment(target.Handle, department)) diff --git a/FivePRS.Server/ServerBrain.Street.cs b/FivePRS.Server/ServerBrain.Street.cs index 4729e50..9e62b74 100644 --- a/FivePRS.Server/ServerBrain.Street.cs +++ b/FivePRS.Server/ServerBrain.Street.cs @@ -1,7 +1,9 @@ using System; using System.Threading.Tasks; using CitizenFX.Core; +using CitizenFX.Core.Native; using FivePRS.Core.Civilian; +using FivePRS.Core.Config; using FivePRS.Core.Events; using FivePRS.Core.Models; using FivePRS.Core.Police; @@ -14,6 +16,9 @@ public partial class ServerBrain { private const string StopPerson = "person"; private const string StopVehicle = "vehicle"; + private const int DriverSeat = -1; + + private static readonly string[] RadarControls = { "front", "rear", "plates" }; private StreetService? _street; @@ -23,6 +28,44 @@ private void RegisterStreetEvents() EventHandlers[EventNames.ServerStopPlate] += new Action(OnStopPlate); EventHandlers[EventNames.ServerRunPlate] += new Action(OnRunPlate); EventHandlers[EventNames.ServerRunPerson] += new Action(OnRunPerson); + EventHandlers[EventNames.ServerPlateRead] += new Action(OnPlateRead); + EventHandlers[EventNames.ServerRadarControl] += new Action(OnRadarControl); + } + + private void OnRadarControl([FromSource] Player player, string control) + { + if (!ConfigManager.Settings.Radar.Enabled || Array.IndexOf(RadarControls, control) < 0) return; + if (!Allow(player, "radarControls", l => l.RadarControls) || !TryGetOfficer(player, out _)) return; + + var ped = API.GetPlayerPed(player.Handle); + var vehicle = API.GetVehiclePedIsIn(ped, false); + if (vehicle == 0) return; + + var driver = API.GetPedInVehicleSeat(vehicle, DriverSeat); + if (driver == 0 || driver == ped) return; + + var owner = API.NetworkGetEntityOwner(driver); + var target = Players[owner]; + if (target is null || API.GetPlayerPed(target.Handle) != driver) return; + + TriggerClientEvent(target, EventNames.ClientRadarControl, control); + } + + private async void OnPlateRead([FromSource] Player player, string plate) + { + if (!ConfigManager.Settings.Radar.PlateReader || _lookup is null) return; + if (!Allow(player, "plateReads", l => l.PlateReads) || !TryGetOfficer(player, out _)) return; + if (!CivilianRules.TryNormalizePlate(plate, out var normalized)) return; + + try + { + var check = await _lookup.CheckPlateAsync(normalized); + TriggerClientEvent(player, EventNames.ClientPlateRead, JsonConvert.SerializeObject(check)); + } + catch (Exception ex) + { + Log.Warn($"Plate read failed for {player.Name}", ex); + } } private void OnRunPlate([FromSource] Player player, string plate, string model, int driverSeed, bool driverFemale, bool hasDriver) => diff --git a/FivePRS.Server/ServerBrain.cs b/FivePRS.Server/ServerBrain.cs index f87e3fa..8131018 100644 --- a/FivePRS.Server/ServerBrain.cs +++ b/FivePRS.Server/ServerBrain.cs @@ -13,6 +13,7 @@ using FivePRS.Core.Models; using FivePRS.Server.Civilian; using FivePRS.Server.Database; +using FivePRS.Server.Framework; using FivePRS.Server.Http; using FivePRS.Server.Logging; using FivePRS.Server.Dispatch; @@ -88,6 +89,8 @@ public ServerBrain() RegisterDiagnostics(); RegisterStreetEvents(); RegisterReportEvents(); + RegisterRadarEvents(); + RegisterFrameworkEvents(); RegisterDeathEvents(); _ = ServerIcon.ApplyDefaultAsync(ConfigManager.Settings.Branding.ServerIcon); @@ -117,8 +120,10 @@ private async Task InitDbAsync() _appearances = new AppearanceService(_db.Civilians, _db.Appearances, () => ConfigManager.Settings.Creator); _roster = new RosterService(_db.Roster); await _roster.LoadAsync(); + await PruneSpeedClocksAsync(); LogStartup(); + await DetectFrameworkAsync(); } catch (Exception ex) when (ex is NotSupportedException || ex is DatabaseSetupException) { @@ -180,6 +185,7 @@ private void OnPlayerDropped([FromSource] Player player, string reason) _rateLimiter.Forget(player.Handle); ClearDowned(ServerId(player)); _dispatch.SetOffDuty(ServerId(player)); + ForgetFrameworkCharacter(player); var license = GetLicense(player); if (license is null) return; @@ -211,6 +217,7 @@ private async void OnPlayerReady([FromSource] Player player) SendPlayerData(player, data); SendEntryOptions(player); SendDownedPlayers(player); + await SyncFrameworkAsync(player); await SendAppearanceAsync(player, license); await SendPreferencesAsync(player, license); @@ -229,9 +236,11 @@ private async void OnEnterService([FromSource] Player player, int departmentId, if (!Enum.IsDefined(typeof(Department), departmentId) || departmentId == (int)Department.None) return; var department = (Department)departmentId; - if (!_permissions.CanJoinDepartment(player.Handle, department)) + if (!CanJoin(player, department)) { - TriggerClientEvent(player, EventNames.ClientEntryRejected, $"You are not authorised to join {department}."); + TriggerClientEvent(player, EventNames.ClientEntryRejected, UsesFramework + ? $"Your character's job doesn't let you join {ConfigManager.DisplayName(department)}." + : $"You are not authorised to join {ConfigManager.DisplayName(department)}."); Audit(AuditActions.PermissionDenied, player, license, $"department {department}"); return; } @@ -251,7 +260,7 @@ private async void OnEnterService([FromSource] Player player, int departmentId, try { - var agency = ConfigManager.Territories.ResolveAgency(department, agencyId)?.Id ?? string.Empty; + var agency = ConfigManager.Territories.ResolveAgency(department, FrameworkAgency(player, department) ?? agencyId)?.Id ?? string.Empty; data.Callsign = normalizedCallsign; if (data.Department != department) @@ -284,7 +293,7 @@ private void SendEntryOptions(Player player) var allowed = new List(); foreach (Department department in Enum.GetValues(typeof(Department))) { - if (_permissions.CanJoinDepartment(player.Handle, department)) + if (CanJoin(player, department)) allowed.Add((int)department); } @@ -297,7 +306,7 @@ private static void HandOverProfile(dynamic deferrals, PlayerData data) { var agency = data.Department == Department.None ? string.Empty - : ConfigManager.Territories.FindAgency(data.Agency)?.Name ?? data.Department.ToString(); + : ConfigManager.Territories.FindAgency(data.Agency)?.Name ?? ConfigManager.DisplayName(data.Department); deferrals.handover(new Dictionary { @@ -323,9 +332,9 @@ private async void OnToggleDuty([FromSource] Player player) if (!data.IsOnDuty && data.Department == Department.None) return; var goingOnDuty = !data.IsOnDuty; - if (goingOnDuty && !_permissions.CanJoinDepartment(player.Handle, data.Department)) + if (goingOnDuty && !CanJoin(player, data.Department)) { - Notify(player, $"~r~You are not authorised to go on duty with {data.Department}."); + Notify(player, $"~r~You are not authorised to go on duty with {ConfigManager.DisplayName(data.Department)}."); Audit(AuditActions.PermissionDenied, player, license, $"duty {data.Department}"); return; } @@ -451,8 +460,16 @@ private async Task AwardXpAsync(int unitId, int baseAmount, string callId) var player = Players[unitId]; if (player is null || !TryGetCached(player, out _, out var data)) return; - var awardedXP = (int)Math.Min(Math.Max(baseAmount * ReadXpMultiplier(), 0), ReadMaxXp()); data.CallsCompleted++; + if (!XpActive) + { + await _db.SavePlayerAsync(data); + SendPlayerData(player, data); + Notify(player, $"~g~CALL #{callId} CLOSED"); + return; + } + + var awardedXP = (int)Math.Min(Math.Max(baseAmount * ReadXpMultiplier(), 0), ReadMaxXp()); try { @@ -483,6 +500,7 @@ private async Task SetDutyAsync(Player player, PlayerData data, bool onDuty) TriggerClientEvent(player, EventNames.ClientDutyStatusChanged, onDuty, (int)data.Department); SendPlayerData(player, data); + SyncFrameworkDuty(player, onDuty); await _db.SavePlayerAsync(data); if (onDuty && ReportService.CanRead(data.Department)) await PushReportsAsync(data.License, null); @@ -511,7 +529,13 @@ private async Task ChangeDepartmentAsync(Player player, PlayerData data, Departm private async Task GrantXpAsync(Player player, PlayerData data, int amount) { + var rank = data.Rank; var rankedUp = data.Ladder().AddXp(data, amount); + if (UsesFramework) + { + data.Rank = rank; + rankedUp = false; + } await _db.SavePlayerAsync(data); SendPlayerData(player, data); @@ -581,8 +605,14 @@ private bool TryGetCached(Player player, out string license, out PlayerData data private void Notify(Player player, string message) => TriggerClientEvent(player, EventNames.ClientNotify, message); - private void SendPlayerData(Player player, PlayerData data) => + private bool XpActive => ConfigManager.Settings.XpEnabled && !UsesFramework; + + private void SendPlayerData(Player player, PlayerData data) + { + data.UsesXp = XpActive; + data.Framework = _framework is null ? null : FrameworkBridge.DisplayName(_framework.Info.Name); TriggerClientEvent(player, EventNames.ClientReceivePlayerData, JsonConvert.SerializeObject(data)); + } private static string? GetLicense(Player player) { diff --git a/FivePRS.Tests/CharacterLinkerTests.cs b/FivePRS.Tests/CharacterLinkerTests.cs new file mode 100644 index 0000000..8cf8001 --- /dev/null +++ b/FivePRS.Tests/CharacterLinkerTests.cs @@ -0,0 +1,172 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using FivePRS.Core.Civilian; +using FivePRS.Core.Config; +using FivePRS.Server.Civilian; +using FivePRS.Server.Framework; +using Xunit; + +namespace FivePRS.Tests +{ + [Collection(TestDatabase.Collection)] + public sealed class CharacterLinkerTests : IAsyncLifetime + { + private const string License = "license:player"; + + private TestDatabase _database = null!; + private CharacterLinker _linker = null!; + private CivilianService _civilians = null!; + private LookupService _lookup = null!; + + public async Task InitializeAsync() + { + _database = await TestDatabase.CreateAsync(); + _linker = new CharacterLinker(_database.Store); + _civilians = new CivilianService(_database.Store, _database.Photos, () => new ResourceSettings(), () => new LicensesConfig(), () => new DateTime(2026, 10, 26)); + _lookup = new LookupService(_database.Store, _database.Photos, () => new ResourceSettings(), () => new LicensesConfig()); + } + + public Task DisposeAsync() + { + _database.Dispose(); + return Task.CompletedTask; + } + + private static ExternalIdentity Identity(string? license = License, string first = "Jane") => new() + { + ExternalId = "qb:ABC123", OwnerLicense = license, FirstName = first, LastName = "Doe", DateOfBirth = "1990-05-04", Gender = "female", + }; + + [Fact] + public async Task Link_CreatesOnceAndUpdatesDetails() + { + var first = await _linker.LinkAsync(Identity()); + var again = await _linker.LinkAsync(Identity(first: "Janet")); + + Assert.Equal(first, again); + var character = await _database.Store.GetCharacterAsync(first); + Assert.Equal("Janet", character!.FirstName); + Assert.Equal("Female", character.Gender); + Assert.Equal("qb:ABC123", character.ExternalId); + Assert.Equal(License, character.OwnerLicense); + } + + [Fact] + public async Task Link_KeepsTheKnownOwnerWhenTheFrameworkDoesNotSay() + { + var placeholder = await _linker.LinkAsync(Identity(license: null)); + Assert.StartsWith(CharacterLinker.PlaceholderOwner, (await _database.Store.GetCharacterAsync(placeholder))!.OwnerLicense); + + await _linker.LinkAsync(Identity()); + await _linker.LinkAsync(Identity(license: null)); + Assert.Equal(License, (await _database.Store.GetCharacterAsync(placeholder))!.OwnerLicense); + } + + [Fact] + public async Task Link_FillsInMissingDetails() + { + var id = await _linker.LinkAsync(new ExternalIdentity { ExternalId = "esx:char1:abc", DateOfBirth = "not a date", Gender = "?" }); + var character = await _database.Store.GetCharacterAsync(id); + + Assert.Equal(CharacterLinker.UnknownName, character!.FirstName); + Assert.Equal(string.Empty, character.DateOfBirth); + Assert.Equal("Male", character.Gender); + } + + [Fact] + public async Task SyncVehicles_AddsMovesAndRemoves() + { + var jane = await _linker.LinkAsync(Identity()); + var other = await _linker.LinkAsync(new ExternalIdentity { ExternalId = "qb:OTHER", OwnerLicense = "license:other", FirstName = "Sam", LastName = "Roe" }); + await _linker.LinkVehicleAsync(other, new ExternalVehicle { Plate = "sold1", Model = "sultan" }); + + await _linker.SyncVehiclesAsync(jane, new[] + { + new ExternalVehicle { Plate = "abc 123", Model = "adder" }, + new ExternalVehicle { Plate = "SOLD1", Model = "sultan" }, + new ExternalVehicle { Plate = "!!", Model = "bad" }, + }); + + var vehicles = await _database.Store.GetVehiclesAsync(jane); + Assert.Equal(new[] { "ABC 123", "SOLD1" }, vehicles.Select(v => v.Plate).OrderBy(p => p)); + Assert.Empty(await _database.Store.GetVehiclesAsync(other)); + + await _linker.SyncVehiclesAsync(jane, new[] { new ExternalVehicle { Plate = "ABC 123" } }); + var remaining = Assert.Single(await _database.Store.GetVehiclesAsync(jane)); + Assert.Equal(CharacterLinker.UnknownModel, remaining.Model); + } + + [Fact] + public async Task ManagedMode_ShowsOnlyTheLinkedCharacterAndLocksEdits() + { + await _civilians.CreateCharacterAsync(License, "Old", "Standalone", "1980-01-01", "Male"); + _civilians.ManagedBy = "QBCore"; + + var empty = await _civilians.GetStateAsync(License); + Assert.Empty(empty.Characters); + Assert.Null(empty.ActiveCharacterId); + Assert.Equal("QBCore", empty.ManagedBy); + + var linked = await _linker.LinkAsync(Identity()); + await _database.Store.TouchCharacterAsync(linked); + var state = await _civilians.GetStateAsync(License); + Assert.Equal(linked, Assert.Single(state.Characters).Id); + Assert.Equal(linked, state.ActiveCharacterId); + + Assert.NotNull(await _civilians.CreateCharacterAsync(License, "New", "Person", "1990-01-01", "Male")); + Assert.NotNull(await _civilians.DeleteCharacterAsync(License, linked)); + Assert.NotNull(await _civilians.RegisterVehicleAsync(License, "NEW1", "Adder")); + } + + [Fact] + public async Task PlateLookup_AsksTheFrameworkForUnknownPlates() + { + var asked = 0; + _lookup.ExternalPlate = async plate => + { + asked++; + if (plate != "FW 1") return false; + var owner = await _linker.LinkAsync(Identity()); + return await _linker.LinkVehicleAsync(owner, new ExternalVehicle { Plate = plate, Model = "adder" }); + }; + + var (found, error) = await _lookup.SearchByPlateAsync("fw 1"); + Assert.Null(error); + Assert.Equal("Jane", found!.Record!.Character.FirstName); + + var (missing, missingError) = await _lookup.SearchByPlateAsync("NOPE"); + Assert.Null(missing); + Assert.Contains("NOPE", missingError); + + await _lookup.SearchByPlateAsync("FW 1"); + Assert.Equal(2, asked); + } + + [Fact] + public async Task Citations_OnLinkedCharactersAreUnpaidUntilCollected() + { + var officer = new OfficerInfo { License = "license:cop", Name = "Officer", Callsign = "1-ADAM-12" }; + var linked = await _linker.LinkAsync(Identity()); + await _civilians.CreateCharacterAsync("license:solo", "Solo", "Player", "1990-01-01", "Male"); + var standalone = (await _database.Store.GetCharactersAsync("license:solo")).Single().Id; + + _lookup.CollectsFines = true; + Assert.Null(await _lookup.IssueRecordAsync(officer, linked, (int)RecordType.Citation, "Speeding", 250)); + Assert.Null(await _lookup.IssueRecordAsync(officer, linked, (int)RecordType.Warning, "Loitering", 0)); + Assert.Null(await _lookup.IssueRecordAsync(officer, standalone, (int)RecordType.Citation, "Speeding", 250)); + + var unpaid = Assert.Single(await _database.Store.GetUnpaidFinesAsync(linked)); + Assert.Equal(250, unpaid.Fine); + Assert.Empty(await _database.Store.GetUnpaidFinesAsync(standalone)); + + await _database.Store.SetFineStatusAsync(unpaid.Id, FineStatus.Paid); + Assert.Empty(await _database.Store.GetUnpaidFinesAsync(linked)); + Assert.Equal(FineStatus.Paid, (await _database.Store.GetRecordsAsync(linked)).Single(r => r.Type == RecordType.Citation).FineStatus); + + _lookup.CollectsFines = false; + Assert.Null(await _lookup.IssueRecordAsync(officer, linked, (int)RecordType.Citation, "Parking", 50)); + Assert.Empty(await _database.Store.GetUnpaidFinesAsync(linked)); + } + } +} diff --git a/FivePRS.Tests/DepartmentConfigTests.cs b/FivePRS.Tests/DepartmentConfigTests.cs new file mode 100644 index 0000000..d9be589 --- /dev/null +++ b/FivePRS.Tests/DepartmentConfigTests.cs @@ -0,0 +1,218 @@ +using System; +using System.IO; +using System.Linq; +using FivePRS.Core.Config; +using FivePRS.Core.Models; +using FivePRS.Server; +using Newtonsoft.Json; +using Xunit; + +namespace FivePRS.Tests +{ + [CollectionDefinition(Name)] + public sealed class ConfigCollection + { + public const string Name = "Static config"; + } + + [Collection(ConfigCollection.Name)] + public class DepartmentConfigTests : IDisposable + { + private readonly string _directory = Path.Combine(Path.GetTempPath(), $"fiveprs-dept-{Guid.NewGuid():N}"); + + private const string Territories = @"""territories"": [ + { ""id"": ""rione_liberta"", ""name"": ""Rione Liberta"", ""polygon"": [[0,0],[10,0],[10,10]] } + ]"; + + [Fact] + public void BadAgency_IsSkippedAndTheRestLoads() + { + var config = ConfigManager.ParseJurisdictions(@"{ " + Territories + @", + ""agencies"": [ + { ""id"": ""cc"", ""name"": ""Comando provinciale Benevento"", ""department"": ""carabinieri"", ""callsignPrefix"": ""CC"", ""territories"": [""rione_liberta""] }, + { ""id"": ""ems"", ""name"": ""118"", ""department"": ""ems"", ""territories"": [""rione_liberta""] } + ] }"); + + Assert.Single(config.Territories); + Assert.Equal(new[] { "ems" }, config.Agencies.Select(a => a.Id)); + } + + [Theory] + [InlineData("police")] + [InlineData("Police")] + [InlineData("POLICE")] + [InlineData(" police ")] + public void Department_IsCaseInsensitive(string value) + { + var config = ConfigManager.ParseJurisdictions(@"{ ""agencies"": [ { ""id"": ""cc"", ""department"": """ + value + @""" } ] }"); + + Assert.Equal(Department.Police, config.Agencies.Single().Department); + } + + [Fact] + public void Department_AcceptsTheConfiguredDisplayName() + { + try + { + ConfigManager.LoadDepartmentInfo(Department.Police, @"{ ""name"": ""Carabinieri"", ""icon"": ""https://example.com/cc.png"" }"); + + var config = ConfigManager.ParseJurisdictions(@"{ ""agencies"": [ { ""id"": ""cc"", ""name"": ""Comando provinciale Benevento"", ""department"": ""carabinieri"", ""icon"": ""https://example.com/benevento.png"" } ] }"); + + Assert.Equal(Department.Police, config.Agencies.Single().Department); + Assert.Equal("Carabinieri", ConfigManager.DisplayName(Department.Police)); + Assert.Equal("https://example.com/cc.png", ConfigManager.IconFor(Department.Police)); + } + finally + { + ConfigManager.LoadDepartmentInfo(Department.Police, null); + } + } + + [Fact] + public void DepartmentInfo_FallsBackToDefaults() + { + ConfigManager.LoadDepartmentInfo(Department.EMS, @"{ ""name"": """", ""icon"": """" }"); + + Assert.Equal("EMS", ConfigManager.DisplayName(Department.EMS)); + Assert.Equal(ConfigManager.Settings.Branding.Departments.Ems, ConfigManager.IconFor(Department.EMS)); + } + + [Fact] + public void DepartmentInfo_WithBrokenJsonKeepsDefaults() + { + ConfigManager.LoadDepartmentInfo(Department.Fire, "{ name: "); + + Assert.Equal("Fire", ConfigManager.DisplayName(Department.Fire)); + } + + [Fact] + public void Agencies_WithoutIdOrDepartmentOrDuplicateIdAreSkipped() + { + var config = ConfigManager.ParseJurisdictions(@"{ ""agencies"": [ + { ""name"": ""No id"", ""department"": ""police"" }, + { ""id"": ""nodept"", ""name"": ""No department"" }, + { ""id"": ""lspd"", ""department"": ""police"" }, + { ""id"": ""LSPD"", ""department"": ""fire"" } + ] }"); + + var agency = Assert.Single(config.Agencies); + Assert.Equal("lspd", agency.Id); + Assert.Equal("lspd", agency.Name); + } + + [Fact] + public void Territories_WithTooFewPointsAreSkipped() + { + var config = ConfigManager.ParseJurisdictions(@"{ ""territories"": [ + { ""id"": ""line"", ""polygon"": [[0,0],[1,1]] }, + { ""id"": ""ok"", ""polygon"": [[0,0],[1,0],[1,1]] } + ] }"); + + Assert.Equal(new[] { "ok" }, config.Territories.Select(t => t.Id)); + } + + [Fact] + public void MissingSections_KeepTheDefaults() + { + var config = ConfigManager.ParseJurisdictions(@"{ ""agencies"": [ { ""id"": ""cc"", ""department"": ""police"" } ] }"); + + Assert.Equal(new JurisdictionConfig().Territories.Count, config.Territories.Count); + } + + [Fact] + public void InvalidJson_UsesDefaults() + { + var config = ConfigManager.ParseJurisdictions("{ \"agencies\": [ "); + + Assert.Equal(new JurisdictionConfig().Agencies.Select(a => a.Id), config.Agencies.Select(a => a.Id)); + } + + [Fact] + public void Icons_IncludeAgencyIcons() + { + var original = ConfigManager.Jurisdictions; + try + { + ConfigManager.LoadJurisdictions(@"{ ""agencies"": [ { ""id"": ""CC"", ""department"": ""police"", ""icon"": ""https://example.com/cc.png"" } ] }"); + + var icons = ConfigManager.Icons(); + + Assert.Equal("https://example.com/cc.png", icons["agency:cc"]); + Assert.True(icons.ContainsKey("police")); + Assert.True(icons.ContainsKey("civilian")); + } + finally + { + ConfigManager.LoadJurisdictions(JsonConvert.SerializeObject(original)); + } + } + + [Fact] + public void FrameworkJob_TakesTheDepartmentFromItsAgency() + { + var original = ConfigManager.Jurisdictions; + try + { + ConfigManager.LoadJurisdictions(@"{ ""agencies"": [ { ""id"": ""cc"", ""department"": ""police"" } ] }"); + var framework = JsonConvert.DeserializeObject(@"{ ""jobs"": { ""carabinieri"": { ""agency"": ""cc"" }, ""nowhere"": { ""agency"": ""missing"" } } }")!; + + var match = framework.Resolve("carabinieri", 0, _ => 10); + + Assert.Equal(Department.Police, match!.Department); + Assert.Equal("cc", match.Agency); + Assert.Null(framework.Resolve("nowhere", 0, _ => 10)); + } + finally + { + ConfigManager.LoadJurisdictions(JsonConvert.SerializeObject(original)); + } + } + + [Fact] + public void ConfigLayout_AddsDepartmentFilesOnce() + { + Assert.Equal(3, ConfigLayout.CreateMissingInfo(_directory)); + Assert.Equal(0, ConfigLayout.CreateMissingInfo(_directory)); + + var json = File.ReadAllText(Path.Combine(_directory, "config", "departments", "ems", "department.json")); + Assert.Equal("EMS", JsonConvert.DeserializeObject(json)!.Name); + } + + [Fact] + public void ShippedDepartmentFiles_UseTheDefaultNames() + { + foreach (var department in ConfigManager.Departments) + { + var path = Path.Combine(RepoRoot(), "config", "departments", ConfigManager.ConfigName(department), "department.json"); + var info = JsonConvert.DeserializeObject(File.ReadAllText(path))!; + Assert.Equal(ConfigManager.DefaultName(department), info.Name); + } + } + + [Fact] + public void ShippedJurisdictions_LoadEveryEntry() + { + var path = Path.Combine(RepoRoot(), "config", "world", "jurisdictions.json"); + var json = File.ReadAllText(path); + + var config = ConfigManager.ParseJurisdictions(json); + + var raw = Newtonsoft.Json.Linq.JObject.Parse(json); + Assert.Equal(((Newtonsoft.Json.Linq.JArray)raw["agencies"]!).Count, config.Agencies.Count); + Assert.Equal(((Newtonsoft.Json.Linq.JArray)raw["territories"]!).Count, config.Territories.Count); + } + + public void Dispose() + { + if (Directory.Exists(_directory)) Directory.Delete(_directory, true); + } + + private static string RepoRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "FivePRS.sln"))) + dir = dir.Parent; + return dir!.FullName; + } + } +} diff --git a/FivePRS.Tests/FrameworkConfigTests.cs b/FivePRS.Tests/FrameworkConfigTests.cs new file mode 100644 index 0000000..39e6c87 --- /dev/null +++ b/FivePRS.Tests/FrameworkConfigTests.cs @@ -0,0 +1,88 @@ +using System.Collections.Generic; +using FivePRS.Core.Config; +using FivePRS.Core.Models; +using Xunit; + +namespace FivePRS.Tests +{ + public sealed class FrameworkConfigTests + { + private static int FiveRanks(Department _) => 5; + + private static string RepoRoot() + { + var dir = new System.IO.DirectoryInfo(System.AppContext.BaseDirectory); + while (dir is not null && !System.IO.File.Exists(System.IO.Path.Combine(dir.FullName, "FivePRS.sln"))) + dir = dir.Parent; + return dir!.FullName; + } + + [Fact] + public void Resolve_MapsDefaultJobsCaseInsensitively() + { + var config = new FrameworkConfig(); + + var police = config.Resolve("Police", 0, FiveRanks); + Assert.Equal(Department.Police, police!.Department); + Assert.Equal("lspd", police.Agency); + Assert.Equal(1, police.Rank); + + Assert.Equal("bcso", config.Resolve("sheriff", 2, FiveRanks)!.Agency); + Assert.Equal(Department.EMS, config.Resolve("ambulance", 1, FiveRanks)!.Department); + Assert.Null(config.Resolve("mechanic", 0, FiveRanks)); + Assert.Null(config.Resolve(null, 0, FiveRanks)); + } + + [Fact] + public void Resolve_UsesGradeMapAndClampsToTheLadder() + { + var config = new FrameworkConfig + { + Jobs = new Dictionary + { + ["police"] = new() { Department = Department.Police, Ranks = new Dictionary { ["0"] = 1, ["1"] = 3 } }, + }, + }; + + Assert.Equal(3, config.Resolve("police", 1, FiveRanks)!.Rank); + Assert.Equal(5, config.Resolve("police", 9, FiveRanks)!.Rank); + Assert.Equal(1, config.Resolve("police", 0, FiveRanks)!.Rank); + } + + [Fact] + public void LoadFramework_ReplacesTheDefaultJobs() + { + ConfigManager.LoadFramework(@"{ ""framework"": ""QBCore"", ""jobs"": { ""lspd_patrol"": { ""department"": ""Police"" } } }"); + try + { + Assert.Equal("qbcore", ConfigManager.Framework.Preferred); + Assert.Single(ConfigManager.Framework.Jobs); + Assert.NotNull(ConfigManager.Framework.Resolve("LSPD_PATROL", 0, FiveRanks)); + Assert.Null(ConfigManager.Framework.Resolve("police", 0, FiveRanks)); + } + finally + { + ConfigManager.LoadFramework(null); + } + + Assert.Equal(FrameworkConfig.Auto, ConfigManager.Framework.Preferred); + Assert.NotNull(ConfigManager.Framework.Resolve("police", 0, FiveRanks)); + } + + [Fact] + public void ShippedFrameworkFile_Loads() + { + var json = System.IO.File.ReadAllText(System.IO.Path.Combine(RepoRoot(), "config", "framework.json")); + ConfigManager.LoadFramework(json); + try + { + Assert.Equal(FrameworkConfig.Auto, ConfigManager.Framework.Preferred); + Assert.Equal("sams", ConfigManager.Framework.Resolve("ambulance", 0, FiveRanks)!.Agency); + } + finally + { + ConfigManager.LoadFramework(null); + } + } + } +} diff --git a/FivePRS.Tests/RadarTests.cs b/FivePRS.Tests/RadarTests.cs new file mode 100644 index 0000000..26f1b9d --- /dev/null +++ b/FivePRS.Tests/RadarTests.cs @@ -0,0 +1,93 @@ +using System.Linq; +using System.Threading.Tasks; +using FivePRS.Core.Civilian; +using FivePRS.Core.Config; +using FivePRS.Core.Police; +using FivePRS.Server.Civilian; +using Xunit; + +namespace FivePRS.Tests +{ + public sealed class RadarSettingsTests + { + [Fact] + public void ToDisplaySpeed_ConvertsToTheChosenUnits() + { + Assert.Equal(45, new RadarSettings { Units = "mph" }.ToDisplaySpeed(20f)); + Assert.Equal(72, new RadarSettings { Units = "kmh" }.ToDisplaySpeed(20f)); + Assert.Equal(72, new RadarSettings { Units = "KM/H" }.ToDisplaySpeed(20f)); + Assert.Equal(0, new RadarSettings().ToDisplaySpeed(0f)); + } + } + + public sealed class PlateFlagsTests + { + [Fact] + public void FromProfile_MatchesTheStreetProfile() + { + var unregistered = Enumerable.Range(0, 2000).Select(i => $"UR{i}").First(p => !StreetProfiles.Vehicle(p).Registered); + Assert.Equal(new[] { PlateFlag.Unregistered }, PlateFlags.FromProfile(unregistered).Flags); + + var stolen = Enumerable.Range(0, 5000).Select(i => $"ST{i}").First(p => StreetProfiles.Vehicle(p).Stolen); + Assert.Contains(PlateFlag.Stolen, PlateFlags.FromProfile(stolen).Flags); + + var wanted = Enumerable.Range(0, 5000).Select(i => $"WA{i}").First(p => + { + var vehicle = StreetProfiles.Vehicle(p); + return vehicle.Registered && !vehicle.DriverIsOwner && StreetProfiles.Person(vehicle.OwnerSeed, vehicle.OwnerFemale).Warrant is not null; + }); + Assert.Contains(PlateFlag.Warrant, PlateFlags.FromProfile(wanted).Flags); + + var driverOwned = Enumerable.Range(0, 2000).Select(i => $"DO{i}").First(p => StreetProfiles.Vehicle(p) is { Registered: true, Stolen: false, DriverIsOwner: true }); + Assert.Empty(PlateFlags.FromProfile(driverOwned).Flags); + } + } + + [Collection(TestDatabase.Collection)] + public sealed class PlateCheckTests : IAsyncLifetime + { + private TestDatabase _database = null!; + private LookupService _lookup = null!; + + public async Task InitializeAsync() + { + _database = await TestDatabase.CreateAsync(); + _lookup = new LookupService(_database.Store, _database.Photos, () => new ResourceSettings(), () => new LicensesConfig()); + } + + public Task DisposeAsync() + { + _database.Dispose(); + return Task.CompletedTask; + } + + [Fact] + public async Task CheckPlate_UsesRecordsForKnownPlates() + { + var owner = await _database.Store.CreateCharacterAsync(new CharacterInfo + { + OwnerLicense = "license:player", FirstName = "Jane", LastName = "Doe", DateOfBirth = "1990-01-01", Gender = "Female", + }); + var vehicle = await _database.Store.AddVehicleAsync(new VehicleInfo { CharacterId = owner, Plate = "JANE1", Model = "Comet" }); + await _database.Store.SetLicenseAsync(owner, StreetProfiles.DriverLicenseType, LicenseStatus.Suspended); + + var clean = await _lookup.CheckPlateAsync("JANE1"); + Assert.Equal("Jane Doe", clean.Owner); + Assert.Equal(new[] { PlateFlag.Suspended }, clean.Flags); + + await _database.Store.SetVehicleStatusAsync(vehicle, VehicleStatus.Stolen); + await _database.Store.AddRecordAsync(new RecordInfo { CharacterId = owner, Type = RecordType.Warrant, Description = "FTA", Active = true }, "license:cop"); + + var flagged = await _lookup.CheckPlateAsync("JANE1"); + Assert.Contains(PlateFlag.Stolen, flagged.Flags); + Assert.Contains(PlateFlag.Warrant, flagged.Flags); + } + + [Fact] + public async Task CheckPlate_DoesNotSaveUnknownPlates() + { + await _lookup.CheckPlateAsync("NPC123"); + Assert.Null(await _database.Store.GetVehicleByPlateAsync("NPC123")); + } + } +} diff --git a/FivePRS.Tests/RankLadderTests.cs b/FivePRS.Tests/RankLadderTests.cs index 88c322a..ea6a601 100644 --- a/FivePRS.Tests/RankLadderTests.cs +++ b/FivePRS.Tests/RankLadderTests.cs @@ -9,6 +9,7 @@ namespace FivePRS.Tests { + [Collection(ConfigCollection.Name)] public class RankLadderTests : IDisposable { private readonly string _directory = Path.Combine(Path.GetTempPath(), $"fiveprs-config-{Guid.NewGuid():N}"); diff --git a/FivePRS.Tests/SpeedClockTests.cs b/FivePRS.Tests/SpeedClockTests.cs new file mode 100644 index 0000000..dc00e07 --- /dev/null +++ b/FivePRS.Tests/SpeedClockTests.cs @@ -0,0 +1,106 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using FivePRS.Core.Civilian; +using FivePRS.Core.Police; +using Xunit; + +namespace FivePRS.Tests +{ + [Collection(TestDatabase.Collection)] + public sealed class SpeedClockTests : IAsyncLifetime + { + private static readonly OfficerInfo Officer = new() { License = "license:cop", Name = "Officer Pixel", Callsign = "1-ADAM-12" }; + private static readonly OfficerInfo Partner = new() { License = "license:partner", Name = "Officer Two", Callsign = "1-ADAM-13" }; + + private TestDatabase _database = null!; + + public async Task InitializeAsync() => _database = await TestDatabase.CreateAsync(); + + public Task DisposeAsync() + { + _database.Dispose(); + return Task.CompletedTask; + } + + private static SpeedClock Clock(int speed, SpeedClockSource source = SpeedClockSource.FrontRadar, string? plate = "ABC 123") + { + var clock = new SpeedClock { Source = source, Speed = speed, Plate = plate, Model = "Buffalo", Location = "Route 68, Harmony" }; + Assert.True(clock.Normalize()); + return clock; + } + + [Fact] + public async Task Recent_ReturnsOnlyTheOfficersClocks_NewestFirst() + { + await _database.SpeedClocks.AddAsync(Clock(61), Officer); + await _database.SpeedClocks.AddAsync(Clock(88, SpeedClockSource.Lidar), Officer); + await _database.SpeedClocks.AddAsync(Clock(45), Partner); + + var clocks = await _database.SpeedClocks.RecentAsync(Officer.License, 50); + + Assert.Equal(new[] { 88, 61 }, clocks.Select(clock => clock.Speed)); + Assert.Equal(SpeedClockSource.Lidar, clocks[0].Source); + Assert.Equal("ABC 123", clocks[0].Plate); + Assert.Equal("Buffalo", clocks[0].Model); + } + + [Fact] + public async Task Recent_KeepsMissingValuesEmpty() + { + await _database.SpeedClocks.AddAsync(Clock(30, plate: null), Officer); + + var clock = Assert.Single(await _database.SpeedClocks.RecentAsync(Officer.License, 50)); + + Assert.Null(clock.Plate); + Assert.Null(clock.Fast); + Assert.Null(clock.Distance); + } + + [Fact] + public async Task Prune_RemovesClocksOlderThanTheCutoff() + { + await _database.SpeedClocks.AddAsync(Clock(50), Officer); + + await _database.SpeedClocks.PruneAsync(DateTime.UtcNow.AddMinutes(1)); + + Assert.Empty(await _database.SpeedClocks.RecentAsync(Officer.License, 50)); + } + + [Theory] + [InlineData(-1)] + [InlineData(SpeedClock.MaxSpeed + 1)] + public void Normalize_RejectsImpossibleSpeeds(int speed) => + Assert.False(new SpeedClock { Speed = speed }.Normalize()); + + [Fact] + public void Normalize_DropsValuesThatDontApply() + { + var clock = new SpeedClock { Source = SpeedClockSource.RearRadar, Speed = 70, Fast = 60, Distance = 40, Units = "furlongs", Plate = "!!", Location = new string('x', 200) }; + + Assert.True(clock.Normalize()); + Assert.Null(clock.Fast); + Assert.Null(clock.Distance); + Assert.Null(clock.Plate); + Assert.Equal("mph", clock.Units); + Assert.Equal(SpeedClock.MaxLocationLength, clock.Location.Length); + } + + [Fact] + public void Normalize_KeepsLidarDistanceAndFasterReadings() + { + var lidar = new SpeedClock { Source = SpeedClockSource.Lidar, Speed = 70, Distance = 120, Units = "kmh" }; + var radar = new SpeedClock { Source = SpeedClockSource.FrontRadar, Speed = 55, Fast = 80 }; + + Assert.True(lidar.Normalize()); + Assert.True(radar.Normalize()); + Assert.Equal(120, lidar.Distance); + Assert.Equal("kmh", lidar.Units); + Assert.Equal(80, radar.Fast); + } + + [Fact] + public void Normalize_RejectsUnknownSources() => + Assert.False(new SpeedClock { Source = (SpeedClockSource)9, Speed = 50 }.Normalize()); + } +} diff --git a/FivePRS.Tests/TestDatabase.cs b/FivePRS.Tests/TestDatabase.cs index 7d6ddee..531dc95 100644 --- a/FivePRS.Tests/TestDatabase.cs +++ b/FivePRS.Tests/TestDatabase.cs @@ -29,6 +29,8 @@ public sealed class TestDatabase : IDisposable public ReportStore Reports { get; private set; } = null!; + public SpeedClockStore SpeedClocks { get; private set; } = null!; + public IDatabaseProvider Provider { get; private set; } = null!; public static async Task CreateAsync() @@ -58,6 +60,7 @@ public static async Task CreateAsync() database.Positions = new PositionStore(provider); database.Photos = new PhotoStore(provider); database.Reports = new ReportStore(provider); + database.SpeedClocks = new SpeedClockStore(provider); return database; } @@ -66,7 +69,7 @@ private static async Task DropTablesAsync(string connectionString) using var conn = new MySqlConnection(connectionString); await conn.OpenAsync(); using var cmd = conn.CreateCommand(); - cmd.CommandText = "DROP TABLE IF EXISTS fiveprs_records, fiveprs_licenses, fiveprs_vehicles, fiveprs_characters, fiveprs_roster, fiveprs_appearances, fiveprs_preferences, fiveprs_positions, fiveprs_audit, fiveprs_schema, ers_players;"; + cmd.CommandText = "DROP TABLE IF EXISTS fiveprs_speed_clocks, fiveprs_reports, fiveprs_photos, fiveprs_records, fiveprs_licenses, fiveprs_vehicles, fiveprs_characters, fiveprs_roster, fiveprs_appearances, fiveprs_preferences, fiveprs_positions, fiveprs_audit, fiveprs_schema, ers_players;"; await cmd.ExecuteNonQueryAsync(); } diff --git a/config/departments/ems/department.json b/config/departments/ems/department.json new file mode 100644 index 0000000..d5b8ac7 --- /dev/null +++ b/config/departments/ems/department.json @@ -0,0 +1,4 @@ +{ + "name": "EMS", + "icon": "" +} diff --git a/config/departments/fire/department.json b/config/departments/fire/department.json new file mode 100644 index 0000000..17494b1 --- /dev/null +++ b/config/departments/fire/department.json @@ -0,0 +1,4 @@ +{ + "name": "Fire", + "icon": "" +} diff --git a/config/departments/police/department.json b/config/departments/police/department.json new file mode 100644 index 0000000..9c189e7 --- /dev/null +++ b/config/departments/police/department.json @@ -0,0 +1,4 @@ +{ + "name": "Police", + "icon": "" +} diff --git a/config/framework.json b/config/framework.json new file mode 100644 index 0000000..9c95bd7 --- /dev/null +++ b/config/framework.json @@ -0,0 +1,17 @@ +{ + "framework": "auto", + "fines": { + "collect": true, + "account": "bank" + }, + "jobs": { + "police": { "department": "Police", "agency": "lspd" }, + "lspd": { "department": "Police", "agency": "lspd" }, + "sheriff": { "department": "Police", "agency": "bcso" }, + "bcso": { "department": "Police", "agency": "bcso" }, + "ambulance": { "department": "EMS", "agency": "sams" }, + "ems": { "department": "EMS", "agency": "sams" }, + "fire": { "department": "Fire", "agency": "lsfd" }, + "lsfd": { "department": "Fire", "agency": "lsfd" } + } +} diff --git a/config/settings.json b/config/settings.json index 55eeb66..7a3292d 100644 --- a/config/settings.json +++ b/config/settings.json @@ -9,6 +9,7 @@ "maxCharacters": 3, "maxVehiclesPerCharacter": 5, "maxFine": 10000, + "xpEnabled": true, "emergencyCallCooldownSeconds": 60, "emergencyCallTimeoutMinutes": 15, "dutyEquipment": "byStart", @@ -29,6 +30,17 @@ "notifyEms": true, "reviveXp": 25 }, + "radar": { + "enabled": true, + "units": "mph", + "range": 150, + "speedAlert": 0, + "plateReader": true, + "plateReaderRange": 35, + "lidar": true, + "lidarRange": 300, + "lidarWeapon": "WEAPON_FLAREGUN" + }, "backup": { "enabled": true, "cooldownSeconds": 30, diff --git a/fxmanifest.lua b/fxmanifest.lua index 0b44f34..1afa9b7 100644 --- a/fxmanifest.lua +++ b/fxmanifest.lua @@ -6,13 +6,14 @@ author 'Pixel ' description 'The Unified Public Response Framework for FiveM.' repository 'https://github.com/FivePRS/core' license 'AGPL-3.0-or-later' -version '0.9.0-ptb.5' +version '0.9.0-ptb.6' lua54 'yes' server_scripts { 'scripts/http.lua', 'scripts/db.lua', + 'scripts/framework.lua', 'server/FivePRS.Server.net.dll', } @@ -43,6 +44,8 @@ files { 'nui/kit.js', 'nui/common.js', 'nui/capture.js', + 'nui/radar.js', + 'nui/radar.css', 'nui/appview.js', 'nui/app-sdk.js', 'nui/menu.js', diff --git a/nui/apps/admin/app.js b/nui/apps/admin/app.js index 1101b68..4d8e6a0 100644 --- a/nui/apps/admin/app.js +++ b/nui/apps/admin/app.js @@ -69,8 +69,7 @@ function renderPanel(player) { setText("panel-name", player.name); setText("panel-license", player.license); - const department = departmentName(player.department); - const ranks = view.ranks?.[department] ?? view.ranks?.Police ?? []; + const ranks = view.ranks?.[String(player.department)] ?? view.ranks?.["1"] ?? []; const rank = document.getElementById("rank"); rank.replaceChildren(...ranks.map((name, index) => { const option = el("option", { text: `${index + 1} · ${name}` }); @@ -166,6 +165,11 @@ function showSection(next) { function render(next) { view = next; + const framework = Boolean(next.framework); + document.getElementById("framework-note").hidden = !framework; + setText("framework-note", framework ? `${next.framework} decides jobs and ranks. Change them there.` : ""); + for (const id of ["rank-control", "department-control", "roster-control"]) document.getElementById(id).hidden = framework; + document.getElementById("xp-control").hidden = !next.xpEnabled; if (!filled) { filled = true; query.value = next.state.query ?? ""; diff --git a/nui/apps/admin/index.html b/nui/apps/admin/index.html index 17fc5fc..d28bb42 100644 --- a/nui/apps/admin/index.html +++ b/nui/apps/admin/index.html @@ -43,20 +43,21 @@

-
+ +
-
+
-
+
-
+

Rostered departments

diff --git a/nui/apps/characters/app.css b/nui/apps/characters/app.css index a4d5e00..d7be937 100644 --- a/nui/apps/characters/app.css +++ b/nui/apps/characters/app.css @@ -362,3 +362,9 @@ body { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.571rem; } + +.managed-note { + padding: 0 0.286rem; + font-size: 0.857rem; + line-height: 1.5; +} diff --git a/nui/apps/characters/app.js b/nui/apps/characters/app.js index 6d2a061..36856d2 100644 --- a/nui/apps/characters/app.js +++ b/nui/apps/characters/app.js @@ -11,6 +11,10 @@ let creating = false; let pendingCount = null; let reviewing = null; +function fineNote(entry) { + return entry.fineStatus === 1 ? " unpaid" : entry.fineStatus === 2 ? " paid" : ""; +} + function showCreate(open) { creating = open; form.hidden = !open; @@ -39,7 +43,7 @@ const recordDots = ["", "bad", "warn", "bad", "info"]; function recordEntry(entry) { const activeWarrant = entry.type === 3 && entry.active; - const meta = [formatDate(entry.createdAt), entry.officerCallsign, entry.fine > 0 ? `$${entry.fine}` : null].filter(Boolean).join(" · "); + const meta = [formatDate(entry.createdAt), entry.officerCallsign, entry.fine > 0 ? `$${entry.fine}${fineNote(entry)}` : null].filter(Boolean).join(" · "); return el("div", { className: "entry" }, [ el("span", { className: `entry-dot ${recordDots[entry.type] ?? ""}` }), el("div", {}, [ @@ -141,6 +145,15 @@ function render(next) { form.hidden = true; } + const managed = state.managedBy; + newButton.hidden = Boolean(managed); + document.getElementById("slots").hidden = Boolean(managed); + document.getElementById("managed-note").hidden = !managed; + setText("managed-note", managed ? `Your characters come from ${managed}. Create, switch and dress them there.` : ""); + const noCharacter = document.getElementById("no-character"); + noCharacter.dataset.text ??= noCharacter.textContent; + noCharacter.textContent = managed ? `Load a character in ${managed} and it shows up here.` : noCharacter.dataset.text; + const active = activeCharacter(next); document.getElementById("characters").replaceChildren(...state.characters.map((character) => characterButton(character, character.id === state.activeCharacterId))); setText("slots", `${state.characters.length} / ${state.maxCharacters}`); @@ -164,10 +177,12 @@ function render(next) { document.getElementById("photo-remove").hidden = !active.photo; const appearance = document.getElementById("appearance"); + appearance.hidden = Boolean(managed); appearance.disabled = Boolean(next.onDuty); - document.getElementById("appearance-note").hidden = !next.onDuty; + document.getElementById("appearance-note").hidden = !next.onDuty || Boolean(managed); const remove = document.getElementById("delete"); + remove.hidden = Boolean(managed); delete remove.dataset.armed; remove.disabled = false; remove.textContent = "Delete"; diff --git a/nui/apps/characters/index.html b/nui/apps/characters/index.html index 74f4419..3e2782c 100644 --- a/nui/apps/characters/index.html +++ b/nui/apps/characters/index.html @@ -18,6 +18,7 @@ New character +
diff --git a/nui/apps/dispatch/app.js b/nui/apps/dispatch/app.js index 6e89221..6ba92b3 100644 --- a/nui/apps/dispatch/app.js +++ b/nui/apps/dispatch/app.js @@ -76,7 +76,7 @@ function renderActive(active, self) { } function renderSelf(self, calls) { - setDepartmentIcon("me-icon", self.department); + setDepartmentIcon("me-icon", self.departmentKey, self.agencyId); setText("me-callsign", self.callsign); setText("me-detail", `${self.name} · ${self.agency} · ${self.territory ?? "Unincorporated"}`); diff --git a/nui/apps/duty/app.js b/nui/apps/duty/app.js index a7ee2a2..1789265 100644 --- a/nui/apps/duty/app.js +++ b/nui/apps/duty/app.js @@ -1,10 +1,13 @@ const enterButton = document.getElementById("enter"); const callsignInput = document.getElementById("callsign"); +const startKey = "fiveprs.dutyStart"; + const startOptions = [ - { id: "here", name: "Here", detail: "Gear and car now" }, + { id: "current", name: "As I am", detail: "Keep your look, no car" }, + { id: "here", name: "Here", detail: "Uniform, gear and car now" }, { id: "teleport", name: "Station", detail: "Teleport and gear up" }, - { id: "drive", name: "Drive there", detail: "GPS route, car waiting" }, + { id: "drive", name: "Drive there", detail: "GPS route to collect gear" }, ]; let view = null; @@ -13,9 +16,22 @@ let entering = false; let toastTimer = null; let selectedDepartment = null; let selectedAgency = null; -let selectedStart = "here"; +let selectedStart = savedStart(); let selectedStation = null; +function savedStart() { + try { + const saved = localStorage.getItem(startKey); + return startOptions.some((option) => option.id === saved) ? saved : "current"; + } catch { + return "current"; + } +} + +function needsStation(start) { + return start === "teleport" || start === "drive"; +} + function departmentById(id) { return view?.departments.find((department) => department.id === id) ?? null; } @@ -63,16 +79,16 @@ function showToast(message) { function renderStarts() { const stations = availableStations(); - document.getElementById("start-step").hidden = stations.length === 0; - if (stations.length === 0) selectedStart = "here"; + const options = stations.length === 0 ? startOptions.filter((option) => !needsStation(option.id)) : startOptions; + if (!options.some((option) => option.id === selectedStart)) selectedStart = "current"; if (!stations.some((station) => station.id === selectedStation)) selectedStation = stations[0]?.id ?? null; document.getElementById("starts").replaceChildren( - ...startOptions.map((option) => choice(option.name, option.detail, option.id === selectedStart, { start: option.id })) + ...options.map((option) => choice(option.name, option.detail, option.id === selectedStart, { start: option.id })) ); const list = document.getElementById("stations"); - list.hidden = selectedStart === "here"; + list.hidden = !needsStation(selectedStart); list.replaceChildren(...stations.map((station) => { const button = el("button", { className: `station${station.id === selectedStation ? " selected" : ""}`, dataset: { station: station.id } }, [ el("span", { text: station.name }), @@ -87,7 +103,7 @@ function renderForm() { const departments = view.departments ?? []; document.getElementById("departments").replaceChildren( ...departments.map((department) => - choice(department.name, null, department.id === selectedDepartment, { department: department.id }, departmentIcon(department.name)) + choice(department.name, null, department.id === selectedDepartment, { department: department.id }, departmentIcon(department.key)) ) ); document.getElementById("no-departments").hidden = departments.length > 0; @@ -97,14 +113,14 @@ function renderForm() { callsignInput.placeholder = `${agency?.callsignPrefix || "UNIT"}-ID`; document.getElementById("agency-step").hidden = agencies.length === 0; document.getElementById("agencies").replaceChildren( - ...agencies.map((item) => choice(item.name, item.callsignPrefix, item.id === selectedAgency, { agency: item.id })) + ...agencies.map((item) => choice(item.name, item.callsignPrefix, item.id === selectedAgency, { agency: item.id }, item.hasIcon ? agencyIcon(item.id) : null)) ); renderStarts(); const station = availableStations().find((item) => item.id === selectedStation); const callsign = callsignInput.value.trim() || callsignInput.placeholder; - setText("summary", [agency?.callsignPrefix, callsign, selectedStart === "here" ? "Here" : station?.name].filter(Boolean).join(" · ")); + setText("summary", [agency?.callsignPrefix, callsign, needsStation(selectedStart) ? station?.name : startOptions.find((option) => option.id === selectedStart)?.name].filter(Boolean).join(" · ")); enterButton.disabled = entering || selectedDepartment === null; enterButton.textContent = entering ? "Going on duty…" : "Go on duty"; @@ -116,6 +132,7 @@ function renderProfile() { setText("rank-name", view.departmentId === 0 ? "Recruit" : view.rankName); setText("rank-detail", view.departmentId === 0 ? "Choose a department to start" : `${view.department} rank ${view.rank} of ${view.rankCount}`); + document.getElementById("progress").hidden = !view.usesXp; const top = view.xpToNext === 0; setText("next-rank", top ? "Top rank" : `Next: ${view.nextRankName}`); setText("xp", top ? `${view.xp} XP` : `${view.xp} / ${view.xpToNext} XP`); @@ -137,7 +154,7 @@ function render(next) { if (view.isOnDuty) { setText("unit-callsign", view.unit?.callsign ?? view.callsign); setText("unit-agency", view.unit?.agency ?? ""); - setDepartmentIcon("unit-icon", view.department); + setDepartmentIcon("unit-icon", view.departmentKey, view.unit?.agencyId); document.getElementById("off").disabled = false; return; } @@ -170,6 +187,9 @@ document.addEventListener("click", (event) => { renderForm(); } else if (target.dataset.start) { selectedStart = target.dataset.start; + try { + localStorage.setItem(startKey, selectedStart); + } catch {} renderForm(); } else if (target.dataset.station) { selectedStation = target.dataset.station; diff --git a/nui/apps/duty/index.html b/nui/apps/duty/index.html index 58a14f5..cac01d5 100644 --- a/nui/apps/duty/index.html +++ b/nui/apps/duty/index.html @@ -18,7 +18,7 @@

-
+
diff --git a/nui/apps/emergency/app.js b/nui/apps/emergency/app.js index cacb638..9937e4b 100644 --- a/nui/apps/emergency/app.js +++ b/nui/apps/emergency/app.js @@ -34,7 +34,7 @@ function renderForm() { document.getElementById("services").replaceChildren(...services.map((service) => { const button = el("button", { className: `service${service.id === selectedService ? " selected" : ""}`, dataset: { service: service.id } }, [ - departmentIcon(service.name), + departmentIcon(service.key), el("span", { className: "service-name", text: service.name }), el("span", { className: "service-detail", text: serviceDetails[service.name.toLowerCase()] ?? "" }), ]); diff --git a/nui/apps/records/app.css b/nui/apps/records/app.css index 241866d..7184477 100644 --- a/nui/apps/records/app.css +++ b/nui/apps/records/app.css @@ -372,6 +372,76 @@ body { display: none; } +.speed { + display: flex; + flex-direction: column; + gap: 0.714rem; +} + +.speed-hint { + margin: 0; + font-size: 0.857rem; +} + +.clock-list { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.clock { + display: flex; + align-items: center; + gap: 1rem; + padding: 0.714rem 1rem; + border: 1px solid var(--line); + border-radius: 0.714rem; + background: var(--surface); +} + +.clock-speed { + display: flex; + flex-direction: column; + align-items: center; + min-width: 4.286rem; +} + +.clock-speed b { + font-size: 1.714rem; + line-height: 1; + color: #f87171; +} + +.clock-speed small { + font-size: 0.714rem; + color: var(--muted); +} + +.clock-body { + display: flex; + flex: 1; + flex-direction: column; + gap: 0.143rem; + min-width: 0; +} + +.clock-plate { + font-weight: 700; +} + +.clock-meta { + overflow: hidden; + font-size: 0.857rem; + color: var(--muted); + text-overflow: ellipsis; + white-space: nowrap; +} + +.clock-actions { + display: flex; + gap: 0.429rem; +} + .reports { display: grid; grid-template-columns: 21.429rem minmax(0, 1fr); diff --git a/nui/apps/records/app.js b/nui/apps/records/app.js index 655548b..4c878ae 100644 --- a/nui/apps/records/app.js +++ b/nui/apps/records/app.js @@ -16,6 +16,9 @@ let toastTimer = null; let shownRecordId = null; let tab = "records"; let reportsRequested = false; +let pendingCitation = null; + +const clockSources = ["Front radar", "Rear radar", "Lidar"]; let selectedReport = null; let shownReportKey = null; @@ -24,6 +27,10 @@ const narrative = document.getElementById("report-narrative"); const medical = () => Boolean(view?.medical); const defaultType = () => (medical() ? 4 : 0); +function fineNote(entry) { + return entry.fineStatus === 1 ? " unpaid" : entry.fineStatus === 2 ? " paid" : ""; +} + function showToast(message) { const toast = document.getElementById("toast"); toast.textContent = message ?? ""; @@ -147,7 +154,7 @@ function renderVehicles(record) { function renderHistory(record) { document.getElementById("history").replaceChildren(...record.records.map((entry) => { const activeWarrant = entry.type === 3 && entry.active; - const meta = [formatDate(entry.createdAt), entry.officerCallsign, entry.fine > 0 ? `$${entry.fine}` : null].filter(Boolean).join(" · "); + const meta = [formatDate(entry.createdAt), entry.officerCallsign, entry.fine > 0 ? `$${entry.fine}${fineNote(entry)}` : null].filter(Boolean).join(" · "); return el("div", { className: "entry" }, [ el("span", { className: `entry-dot ${recordDots[entry.type] ?? ""}` }), el("div", {}, [ @@ -168,11 +175,16 @@ function renderHistory(record) { } function showTab(next) { - tab = view?.medical ? next : "records"; + const allowed = view?.medical ? ["records", "reports"] : ["records", "speed"]; + const changed = tab !== next; + tab = allowed.includes(next) ? next : "records"; for (const node of document.querySelectorAll("[data-tab]")) node.classList.toggle("active", node.dataset.tab === tab); document.getElementById("records-view").hidden = tab !== "records"; search.hidden = tab !== "records"; document.getElementById("reports-view").hidden = tab !== "reports"; + document.getElementById("speed-view").hidden = tab !== "speed"; + + if (tab === "speed" && (changed || !view?.clocks)) FivePRS.action("clocks"); if (tab === "reports" && !reportsRequested) { reportsRequested = true; @@ -180,6 +192,61 @@ function showTab(next) { } } +function clockText(clock) { + const units = clock.units === "kmh" ? "km/h" : "mph"; + const fast = clock.fast ? ` (fastest ${clock.fast} ${units})` : ""; + const range = clock.distance !== null && clock.distance !== undefined ? ` at ${clock.distance} m` : ""; + const place = clock.location ? ` on ${clock.location}` : ""; + return `Clocked at ${clock.speed} ${units}${fast} by ${clockSources[clock.source]?.toLowerCase() ?? "radar"}${range}${place}, ${dateTime(clock.createdAt)}.`; +} + +function clockItem(clock) { + const units = clock.units === "kmh" ? "km/h" : "mph"; + const details = [clockSources[clock.source] ?? "Radar", clock.model, clock.location, dateTime(clock.createdAt)].filter(Boolean).join(" · "); + const actions = clock.plate + ? [button("Run plate", "button small", { clockRun: clock.id }), button("Cite", "button small primary", { clockCite: clock.id })] + : []; + return el("div", { className: "clock" }, [ + el("span", { className: "clock-speed mono" }, [el("b", { text: clock.speed }), el("small", { text: units })]), + el("div", { className: "clock-body" }, [ + el("span", { className: "clock-plate mono", text: clock.plate ?? "No plate" }), + el("span", { className: "clock-meta", text: details }), + clock.fast ? el("span", { className: "clock-meta", text: `Fastest ${clock.fast} ${units}` }) : null, + ]), + el("div", { className: "clock-actions" }, actions), + ]); +} + +function renderClocks() { + const clocks = view?.clocks ?? []; + document.getElementById("clocks").replaceChildren(...clocks.map(clockItem)); + document.getElementById("clocks-empty").hidden = !view?.clocks || clocks.length > 0; +} + +function runClockPlate(id, cite) { + const clock = (view?.clocks ?? []).find((entry) => entry.id === id); + if (!clock?.plate) return; + pendingCitation = cite ? clockText(clock) : null; + showTab("records"); + setSearchMode("plate"); + term.value = clock.plate; + showToast(cite ? "Pick the driver to fill in the citation." : null); + FivePRS.action("searchPlate", { plate: clock.plate }); +} + +function applyPendingCitation() { + if (!pendingCitation || medical()) return; + setEntryType(0); + const offences = view?.offences ?? []; + const index = offences.findIndex((item) => /speed/i.test(item.label)); + if (index >= 0) { + offence.value = String(index); + fine.value = String(Math.min(offences[index].fine, view.maxFine)); + } + notes.value = `${index >= 0 ? `${offences[index].label}. ` : ""}${pendingCitation}`; + pendingCitation = null; +} + function dateTime(value) { const date = new Date(value); return Number.isNaN(date.getTime()) ? "" : date.toLocaleString([], { month: "short", day: "numeric", year: "numeric", hour: "2-digit", minute: "2-digit" }); @@ -301,6 +368,7 @@ function renderRecord(record) { shownRecordId = person.id; entryForm.reset(); setEntryType(defaultType()); + applyPendingCitation(); } } @@ -324,6 +392,7 @@ function render(next) { showTab(tab); if (next.medical) renderReports(); + else renderClocks(); renderStop(); renderResults(); @@ -389,6 +458,10 @@ document.addEventListener("click", (event) => { if (target.dataset.tab) { showTab(target.dataset.tab); + } else if (target.dataset.clockRun || target.dataset.clockCite) { + runClockPlate(Number(target.dataset.clockRun || target.dataset.clockCite), Boolean(target.dataset.clockCite)); + } else if (target.id === "clocks-refresh") { + FivePRS.action("clocks"); } else if (target.dataset.report) { selectedReport = target.dataset.report; renderReports(); diff --git a/nui/apps/records/index.html b/nui/apps/records/index.html index 03e0102..90865e5 100644 --- a/nui/apps/records/index.html +++ b/nui/apps/records/index.html @@ -9,9 +9,10 @@
-
+
- + +