Skip to content

Commit

Permalink
Add a tensy bit of resiliency and throttling
Browse files Browse the repository at this point in the history
  • Loading branch information
insomniac-eeper committed May 30, 2024
1 parent b945748 commit 48df743
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
11 changes: 11 additions & 0 deletions BTTDRichDiscordPresence/BTTDRichPresence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace BTTDRichDiscordPresence;

using Discord;
using System;
using UnityEngine;

/// <summary>
Expand All @@ -19,6 +20,8 @@ public class BTTDRichPresence : MonoBehaviour
private int currentMapId = -1;
private int reportedMapId = -999;

private long lastActivityUpdateTimestamp;

/// <summary>
/// Runs once script is initialized regardless of enabled state.
/// </summary>
Expand All @@ -30,6 +33,7 @@ public void Awake()
this.DefineHooks();
this.discordRichPresence ??= new DiscordRichPresence();
this.discordRichPresence.Start();
lastActivityUpdateTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
}

/// <summary>
Expand All @@ -56,6 +60,13 @@ public void Update()
/// </remarks>
private bool ShouldUpdateActivity()
{
var now = DateTimeOffset.Now.ToUnixTimeSeconds();
if (now - this.lastActivityUpdateTimestamp < 5)
{
return false;
}

lastActivityUpdateTimestamp = now;
return this.currentMapId != this.reportedMapId;
}

Expand Down
29 changes: 16 additions & 13 deletions BTTDRichDiscordPresence/DiscordRichPresence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,30 +97,33 @@ public void Update()
{
if (this.client == null)
{
if (this.lastAttemptTimestamp + Constants.RetryDelay < DateTimeOffset.Now.ToUnixTimeSeconds())
var now = DateTimeOffset.Now.ToUnixTimeSeconds();
if (this.lastAttemptTimestamp + Constants.RetryDelay < now)
{
if (this.retries < Constants.MaxRetries)
{
this.retries++;
_ = this.RegisterClient();
}
else
{
Plugin.Log.LogWarning("Max retries for connecting to client reached.");
return;
}
_ = this.RegisterClient();
this.lastAttemptTimestamp = now;
}
}

this.client?.RunCallbacks();
try
{
this.client?.RunCallbacks();
}
catch (Exception ex)
{
Plugin.Log.LogWarning("Failed to run callbacks: " + ex.Message);
this.client?.Dispose();
this.client = null;
}

}

private bool RegisterClient()
{
this.lastAttemptTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
try
{
this.client = new Discord(Constants.AppId, (ulong)CreateFlags.Default);
this.client = new Discord(Constants.AppId, (ulong)CreateFlags.NoRequireDiscord);
Plugin.Log.LogInfo("Client created.");
}
catch (Exception ex)
Expand Down

0 comments on commit 48df743

Please sign in to comment.