add set client meta and inc/dec to framework

This commit is contained in:
RaidMax 2022-02-10 16:50:45 -06:00
parent aa6ae0ab8d
commit c9cf7be341
4 changed files with 277 additions and 42 deletions

View File

@ -68,6 +68,29 @@ namespace IW4MAdmin.Application.Misc
await ctx.SaveChangesAsync();
}
public async Task SetPersistentMeta(string metaKey, string metaValue, int clientId)
{
await AddPersistentMeta(metaKey, metaValue, new EFClient { ClientId = clientId });
}
public async Task IncrementPersistentMeta(string metaKey, int incrementAmount, int clientId)
{
var existingMeta = await GetPersistentMeta(metaKey, new EFClient { ClientId = clientId });
if (!long.TryParse(existingMeta?.Value ?? "0", out var existingValue))
{
existingValue = 0;
}
var newValue = existingValue + incrementAmount;
await SetPersistentMeta(metaKey, newValue.ToString(), clientId);
}
public async Task DecrementPersistentMeta(string metaKey, int decrementAmount, int clientId)
{
await IncrementPersistentMeta(metaKey, -decrementAmount, clientId);
}
public async Task AddPersistentMeta(string metaKey, string metaValue)
{
await using var ctx = _contextFactory.CreateContext();

View File

@ -11,13 +11,16 @@ init()
level.eventBus.outVar = "sv_iw4madmin_out";
level.eventBus.failKey = "fail";
level.eventBus.timeoutKey = "timeout";
level.eventBus.timeout = 10;
level.eventBus.timeout = 30;
level.clientDataKey = "clientData";
level.eventTypes = spawnstruct();
level.eventTypes.localClientEvent = "client_event";
level.eventTypes.clientDataReceived = "ClientDataReceived";
level.eventTypes.clientDataRequested = "ClientDataRequested";
level.eventTypes.setClientDataRequested = "SetClientDataRequested";
level.eventTypes.setClientDataCompleted = "SetClientDataCompleted";
level.eventTypes.executeCommandRequested = "ExecuteCommandRequested";
SetDvarIfUninitialized( level.eventBus.inVar, "" );
@ -29,9 +32,10 @@ init()
level.eventCallbacks = [];
level.eventCallbacks[level.eventTypes.clientDataReceived] = ::OnClientDataReceived;
level.eventCallbacks[level.eventTypes.executeCommandRequested] = ::OnExecuteCommand;
level.eventCallbacks[level.eventTypes.setClientDataCompleted] = ::OnSetClientDataCompleted;
// start long running tasks
level thread PlayerWaitEvents();
level thread MonitorClientEvents();
level thread MonitorBus();
level thread OnPlayerConnect();
}
@ -56,6 +60,7 @@ OnPlayerConnect()
}
player thread OnPlayerSpawned();
player thread PlayerTrackingOnInterval();
}
}
@ -70,17 +75,42 @@ OnPlayerSpawned()
}
}
OnPlayerDisconnect()
{
level endon ( "disconnect" );
for ( ;; )
{
self waittill( "disconnect" );
self SaveTrackingMetrics();
}
}
OnGameEnded()
{
level endon ( "disconnect" );
for ( ;; )
{
level waittill( "game_ended" );
// note: you can run data code here but it's possible for
// data to get trucated, so we will try a timer based approach for now
}
}
DisplayWelcomeData()
{
self endon( "disconnect" );
clientData = self.pers[level.clientDataKey];
if ( clientData.permissionLevel != "User" )
if ( clientData.permissionLevel == "User" || clientData.permissionLevel == "Flagged" )
{
self IPrintLnBold( "Welcome, your level is ^5" + clientData.permissionLevel );
return;
}
wait (2.0);
self IPrintLnBold( "Welcome, your level is ^5" + clientData.permissionLevel );
wait( 2.0 );
self IPrintLnBold( "You were last seen ^5" + clientData.lastConnection );
}
@ -91,6 +121,7 @@ PlayerConnectEvents()
clientData = self.pers[level.clientDataKey];
// this gives IW4MAdmin some time to register the player before making the request;
// although probably not necessary some users might have a slow database or poll rate
wait ( 2 );
if ( isDefined( clientData.state ) && clientData.state == "complete" )
@ -103,14 +134,28 @@ PlayerConnectEvents()
// self RequestClientMeta( "LastServerPlayed" );
}
PlayerWaitEvents()
PlayerTrackingOnInterval()
{
level endon( "game_ended" );
self endon( "disconnect" );
for ( ;; )
{
level waittill( "client_event", client );
wait ( 120 );
if ( IsAlive( self ) )
{
self SaveTrackingMetrics();
}
}
}
MonitorClientEvents()
{
level endon( "disconnect" );
self endon( "disconnect" );
for ( ;; )
{
level waittill( level.eventTypes.localClientEvent, client );
if ( level.iw4adminIntegrationDebug == 1 )
{
@ -135,16 +180,81 @@ PlayerWaitEvents()
RequestClientMeta( metaKey )
{
getClientMetaEvent = BuildEventRequest( true, level.eventTypes.clientDataRequested, "Meta", self, metaKey );
self thread QueueEvent( getClientMetaEvent, level.eventTypes.clientDataRequested );
level thread QueueEvent( getClientMetaEvent, level.eventTypes.clientDataRequested, self );
}
RequestClientBasicData()
{
getClientDataEvent = BuildEventRequest( true, level.eventTypes.clientDataRequested, "None", self, "" );
self thread QueueEvent( getClientDataEvent, level.eventTypes.clientDataRequested );
level thread QueueEvent( getClientDataEvent, level.eventTypes.clientDataRequested, self );
}
BuildEventRequest( responseExpected, eventType, eventSubtype, client, data )
IncrementClientMeta( metaKey, incrementValue, clientId )
{
SetClientMeta( metaKey, incrementValue, clientId, "increment" );
}
DecrementClientMeta( metaKey, decrementValue, clientId )
{
SetClientMeta( metaKey, decrementValue, clientId, "decrement" );
}
SetClientMeta( metaKey, metaValue, clientId, direction )
{
data = "key=" + metaKey + "|value=" + metaValue;
clientNumber = -1;
if ( IsDefined ( clientId ) )
{
data = data + "|clientId=" + clientId;
clientNumber = -1;
}
if ( IsDefined( direction ) )
{
data = data + "|direction=" + direction;
}
if ( IsPlayer( self ) )
{
clientNumber = self getEntityNumber();
}
setClientMetaEvent = BuildEventRequest( true, level.eventTypes.setClientDataRequested, "Meta", clientNumber, data );
level thread QueueEvent( setClientMetaEvent, level.eventTypes.setClientDataRequested, self );
}
SaveTrackingMetrics()
{
if ( level.iw4adminIntegrationDebug == 1 )
{
self IPrintLn( "Saving tracking metrics for " + self.persistentClientId );
}
currentShotCount = self getPlayerStat( "mostshotsfired" );
change = currentShotCount - self.lastShotCount;
if ( level.iw4adminIntegrationDebug == 1 )
{
self IPrintLn( "Total Shots Fired increased by " + change );
}
if ( !IsDefined( change ) )
{
change = 0;
}
if ( change == 0 )
{
return;
}
IncrementClientMeta( "TotalShotsFired", change, self.persistentClientId );
self.lastShotCount = currentShotCount;
}
BuildEventRequest( responseExpected, eventType, eventSubtype, entOrId, data )
{
if ( !isDefined( data ) )
{
@ -156,6 +266,11 @@ BuildEventRequest( responseExpected, eventType, eventSubtype, client, data )
eventSubtype = "None";
}
if ( IsPlayer( entOrId ) )
{
entOrId = entOrId getEntityNumber();
}
request = "0";
if ( responseExpected )
@ -163,7 +278,7 @@ BuildEventRequest( responseExpected, eventType, eventSubtype, client, data )
request = "1";
}
request = request + ";" + eventType + ";" + eventSubtype + ";" + client getEntityNumber() + ";" + data;
request = request + ";" + eventType + ";" + eventSubtype + ";" + entOrId + ";" + data;
return request;
}
@ -173,7 +288,7 @@ MonitorBus()
for( ;; )
{
wait ( 0.25 );
wait ( 0.1 );
// check to see if IW4MAdmin is ready to receive more data
if ( getDvar( level.eventBus.inVar ) == "" )
@ -198,12 +313,12 @@ MonitorBus()
}
}
QueueEvent( request, eventType )
QueueEvent( request, eventType, notifyEntity )
{
self endon( "disconnect" );
level endon( "disconnect" );
start = GetTime();
maxWait = level.eventBus.timeout * 1000; // 10 seconds
maxWait = level.eventBus.timeout * 1000; // 30 seconds
timedOut = "";
while ( GetDvar( level.eventBus.inVar ) != "" && ( GetTime() - start ) < maxWait )
@ -214,7 +329,7 @@ QueueEvent( request, eventType )
{
if ( level.iw4adminIntegrationDebug == 1 )
{
self IPrintLn( "A request is already in progress..." );
IPrintLn( "A request is already in progress..." );
}
timedOut = "set";
continue;
@ -227,10 +342,13 @@ QueueEvent( request, eventType )
{
if ( level.iw4adminIntegrationDebug == 1 )
{
self IPrintLn( "Timed out waiting for response..." );
IPrintLn( "Timed out waiting for response..." );
}
NotifyClientEventTimeout( eventType );
if ( IsDefined( notifyEntity) )
{
notifyEntity NotifyClientEventTimeout( eventType );
}
return;
}
@ -287,7 +405,7 @@ NotifyClientEvent( eventInfo )
client.event = event;
level notify( "client_event", client );
level notify( level.eventTypes.localClientEvent, client );
}
//////////////////////////////////
@ -311,20 +429,22 @@ OnClientDataReceived( event )
if ( event.subtype == "Meta" )
{
if ( !isDefined( clientData["meta"] ) )
if ( !isDefined( clientData.meta ) )
{
clientData.meta = [];
}
metaKey = event.data[0];
clientData["meta"][metaKey] = event.data[metaKey];
clientData.meta[metaKey] = event.data[metaKey];
return;
}
clientData.permissionLevel = event.data["level"];
clientData.clientId = event.data["clientId"];
clientData.lastConnection = event.data["lastConnection"];
clientData.state = "complete";
self.persistentClientId = event.data["clientId"];
self thread DisplayWelcomeData();
}
@ -355,6 +475,16 @@ OnExecuteCommand( event )
}
}
OnSetClientDataCompleted( event )
{
// IW4MAdmin let us know it persisted (success or fail)
if ( level.iw4adminIntegrationDebug == 1 )
{
IPrintLn( "Set Client Data -> subtype = " + event.subType + " status = " + event.data["status"] );
}
}
//////////////////////////////////
// Command Implementations
/////////////////////////////////

View File

@ -45,11 +45,6 @@ let plugin = {
timer.Start(0, pollRate);
}
break;
case 'disconnect':
if (server.ClientNum === 0 && servers[server.EndPoint] != null) {
servers[server.EndPoint].timer.Stop();
}
break;
case 'warn':
const warningTitle = _localization.LocalizationIndex['GLOBAL_WARNING'];
sendScriptCommand(server, 'Alert', gameEvent.Target, {
@ -264,7 +259,7 @@ const parseEvent = (input) => {
eventType: eventInfo[1],
subType: eventInfo[2],
clientNumber: eventInfo[3],
data: eventInfo.length > 4 ? eventInfo [4] : undefined
data: eventInfo.length > 4 ? parseDataString(eventInfo[4]) : undefined
}
}
@ -328,6 +323,7 @@ const pollForEvents = server => {
logger.WriteDebug(`Processing input... ${event.eventType} ${event.subType} ${event.data} ${event.clientNumber}`);
// todo: refactor to mapping if possible
if (event.eventType === 'ClientDataRequested') {
const client = server.GetClientByNumber(event.clientNumber);
@ -338,11 +334,12 @@ const pollForEvents = server => {
if (event.subType === 'Meta') {
const metaService = _serviceResolver.ResolveService('IMetaService');
const meta = metaService.GetPersistentMeta(event.data, client).Result;
const meta = metaService.GetPersistentMeta(event.data, client).GetAwaiter().GetResult().Value;
data[event.data] = meta === null ? '' : meta.Value;
} else {
data = {
level: client.Level,
clientId: client.ClientId,
lastConnection: client.LastConnection
};
}
@ -350,7 +347,42 @@ const pollForEvents = server => {
sendEvent(server, false, 'ClientDataReceived', event.subType, client, data);
} else {
logger.WriteWarning(`Could not find client slot ${event.clientNumber} when processing ${event.eventType}`);
sendEvent(server, false, 'ClientDataReceived', 'Fail', { ClientNumber: event.clientNumber }, undefined);
sendEvent(server, false, 'ClientDataReceived', 'Fail', {ClientNumber: event.clientNumber}, undefined);
}
}
if (event.eventType === 'SetClientDataRequested') {
let client = server.GetClientByNumber(event.clientNumber);
let clientId;
if (client != null){
clientId = client.ClientId;
} else {
clientId = parseInt(event.data.clientId);
}
logger.WriteDebug(`ClientId=${clientId}`);
if (clientId == null) {
logger.WriteWarning(`Could not find client slot ${event.clientNumber} when processing ${event.eventType}`);
sendEvent(server, false, 'SetClientDataCompleted', 'Meta', {ClientNumber: event.clientNumber}, {status: 'Fail'});
} else {
if (event.subType === 'Meta') {
const metaService = _serviceResolver.ResolveService('IMetaService');
try {
logger.WriteDebug(`Key=${event.data['key']}, Value=${event.data['value']}`);
if (event.data['direction'] != null) {
event.data['direction'] = 'up'
? metaService.IncrementPersistentMeta(event.data['key'], event.data['value'], clientId).GetAwaiter().GetResult()
: metaService.DecrementPersistentMeta(event.data['key'], event.data['value'], clientId).GetAwaiter().GetResult();
} else {
metaService.SetPersistentMeta(event.data['key'], event.data['value'], clientId).GetAwaiter().GetResult();
}
sendEvent(server, false, 'SetClientDataCompleted', 'Meta', {ClientNumber: event.clientNumber}, {status: 'Complete'});
} catch (error) {
sendEvent(server, false, 'SetClientDataCompleted', 'Meta', {ClientNumber: event.clientNumber}, {status: 'Fail'});
}
}
}
}
@ -360,6 +392,9 @@ const pollForEvents = server => {
logger.WriteError(`Could not reset in bus value for ${server.EndPoint} - ${error}`);
}
}
else if (server.ClientNum === 0) {
servers[server.EndPoint].timer.Stop();
}
}
const buildDataString = data => {
@ -375,3 +410,21 @@ const buildDataString = data => {
return formattedData.substring(0, Math.max(0, formattedData.length - 1));
}
const parseDataString = data => {
if (data === undefined) {
return '';
}
const dict = {}
for (const segment of data.split('|')) {
const keyValue = segment.split('=');
if (keyValue.length !== 2) {
continue;
}
dict[keyValue[0]] = keyValue[1];
}
return dict.length === 0 ? data : dict;
}

View File

@ -19,6 +19,35 @@ namespace SharedLibraryCore.Interfaces
/// <returns></returns>
Task AddPersistentMeta(string metaKey, string metaValue, EFClient client, EFMeta linkedMeta = null);
/// <summary>
/// adds or updates meta key and value to the database
/// </summary>
/// <param name="metaKey">key of meta data</param>
/// <param name="metaValue">value of the meta data</param>
/// <param name="clientId">id of the client to save the meta for</param>
/// <returns></returns>
Task SetPersistentMeta(string metaKey, string metaValue, int clientId);
/// <summary>
/// increments meta value and persists to the database
/// <remarks>if the meta value does not already exist it will be set to the increment amount</remarks>
/// </summary>
/// <param name="metaKey">key of meta data</param>
/// <param name="incrementAmount">value to increment by</param>
/// <param name="clientId">id of the client to save the meta for</param>
/// <returns></returns>
Task IncrementPersistentMeta(string metaKey, int incrementAmount, int clientId);
/// <summary>
/// decrements meta value and persists to the database
/// <remarks>if the meta value does not already exist it will be set to the decrement amount</remarks>
/// </summary>
/// <param name="metaKey">key of meta data</param>
/// <param name="decrementAmount">value to increment by</param>
/// <param name="clientId">id of the client to save the meta for</param>
/// <returns></returns>
Task DecrementPersistentMeta(string metaKey, int decrementAmount, int clientId);
/// <summary>
/// adds or updates meta key and value to the database
/// </summary>