Skip to content
Permalink
Browse files

Beefed up game service

  • Loading branch information...
kellyelton committed Oct 11, 2016
1 parent eb048e5 commit de75cfc9b961a03dad495d09bc49af18b8a12eea
@@ -23,6 +23,7 @@
*_p.c
*.orig
.svn
.vs
/octgnFX/CassiniDev/CassiniDev/bin
/octgnFX/CassiniDev/CassiniDev/obj
/octgnFX/ConsoleHelper/bin
@@ -79,6 +79,8 @@ public void StopListening()

try
{
Client.Client.Disconnect(true);
Client.Client.Dispose();
Client.Close();
}
catch
@@ -1,4 +1,7 @@
using System;
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
using System;
using System.Diagnostics;
using System.Reflection;
using log4net;
@@ -31,10 +31,8 @@ public class GameBot : IDisposable

private static readonly object GameBotSingletonLocker = new object();

public static GameBot Instance
{
get
{
public static GameBot Instance {
get {
if (SingletonContext == null)
{
lock (GameBotSingletonLocker)
@@ -51,110 +49,125 @@ public static GameBot Instance

#endregion Singleton

private readonly MemoryCache _userRequests;
private readonly Timer _refreshGamesTimer;
private XmppClientConnection _xmpp;
public ObjectHandler OnCheckRecieved { get; set; }

private GameBot()
{
refreshGamesTimer.Start();
refreshGamesTimer.Elapsed += RefreshGamesTimerOnElapsed;
_userRequests = new MemoryCache(nameof(_userRequests));
_refreshGamesTimer = new Timer(2000);
_refreshGamesTimer.Start();
_refreshGamesTimer.Elapsed += RefreshGamesTimerOnElapsed;
}

private void RefreshGamesTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
refreshGamesTimer.Enabled = false;
_refreshGamesTimer.Enabled = false;

if (userRequests.GetCount() == 0) return;
if (_userRequests.GetCount() == 0) return;
var games = GameManager.Instance.Games.ToArray();

foreach (var game in games)
{
var strname = "hostrequest_" + game.Id;
if (userRequests.Contains(strname))
if (_userRequests.Contains(strname))
{
userRequests.Remove(strname);
_userRequests.Remove(strname);

SendGameReady(game);
}
}

}
catch(Exception e)
{
Log.Error("[RefreshGamesTimerOnElapsed]", e);
}
finally
{
refreshGamesTimer.Enabled = true;
_refreshGamesTimer.Enabled = true;
}
}

private readonly MemoryCache userRequests = new MemoryCache("userRequests");

private readonly Timer refreshGamesTimer = new Timer(2000);

private XmppClientConnection Xmpp { get; set; }

public ObjectHandler OnCheckRecieved { get; set; }

public void Start()
{
RemakeXmpp();
}

public void RemakeXmpp()
{
if (Xmpp != null)
if (_xmpp != null)
{
Xmpp.OnXmppConnectionStateChanged -= XmppOnOnXmppConnectionStateChanged;
Xmpp.OnMessage -= XmppOnOnMessage;
Xmpp.OnError -= XmppOnOnError;
Xmpp.OnAuthError -= Xmpp_OnAuthError;
Xmpp.OnStreamError -= XmppOnOnStreamError;
Xmpp.OnAgentStart -= XmppOnOnAgentStart;
Xmpp.Close();
Xmpp = null;
_xmpp.OnXmppConnectionStateChanged -= XmppOnOnXmppConnectionStateChanged;
_xmpp.OnMessage -= XmppOnOnMessage;
_xmpp.OnError -= XmppOnOnError;
_xmpp.OnAuthError -= Xmpp_OnAuthError;
_xmpp.OnStreamError -= XmppOnOnStreamError;
_xmpp.OnAgentStart -= XmppOnOnAgentStart;
_xmpp.Close();
_xmpp = null;
}
Xmpp = new XmppClientConnection(AppConfig.Instance.ServerPath);
_xmpp = new XmppClientConnection(AppConfig.Instance.ServerPath);
ElementFactory.AddElementType("hostgamerequest", "octgn:hostgamerequest", typeof(HostGameRequest));

Xmpp.RegisterAccount = false;
Xmpp.AutoAgents = true;
Xmpp.AutoPresence = true;
Xmpp.AutoRoster = true;
Xmpp.Username = AppConfig.Instance.XmppUsername;
Xmpp.Password = AppConfig.Instance.XmppPassword;
Xmpp.Priority = 1;
Xmpp.OnMessage += XmppOnOnMessage;
Xmpp.OnError += XmppOnOnError;
Xmpp.OnAuthError += Xmpp_OnAuthError;
Xmpp.OnStreamError += XmppOnOnStreamError;
Xmpp.KeepAlive = true;
Xmpp.KeepAliveInterval = 60;
Xmpp.OnAgentStart += XmppOnOnAgentStart;
Xmpp.OnXmppConnectionStateChanged += XmppOnOnXmppConnectionStateChanged;
Xmpp.Open();
_xmpp.RegisterAccount = false;
_xmpp.AutoAgents = true;
_xmpp.AutoPresence = true;
_xmpp.AutoRoster = true;
_xmpp.Username = AppConfig.Instance.XmppUsername;
_xmpp.Password = AppConfig.Instance.XmppPassword;
_xmpp.Priority = 1;
_xmpp.OnMessage += XmppOnOnMessage;
_xmpp.OnError += XmppOnOnError;
_xmpp.OnAuthError += Xmpp_OnAuthError;
_xmpp.OnStreamError += XmppOnOnStreamError;
_xmpp.KeepAlive = true;
_xmpp.KeepAliveInterval = 60;
_xmpp.OnAgentStart += XmppOnOnAgentStart;
_xmpp.OnXmppConnectionStateChanged += XmppOnOnXmppConnectionStateChanged;
_xmpp.Open();
}

public void SendGameReady(HostedGameData game)
{
var m = new Message(game.Username + "@of.octgn.net", MessageType.normal, "", "gameready");
m.GenerateId();
m.AddChild(game);
Xmpp.Send(m);
_xmpp.Send(m);
}

private void XmppOnOnStreamError(object sender, Element element)
{
var textTag = element.GetTag("text");
if (!String.IsNullOrWhiteSpace(textTag) && textTag.Trim().ToLower() == "replaced by new connection")
Log.Error("Someone Logged In As GameBot");
try
{
var textTag = element.GetTag("text");
if ("replaced by new connection".Equals(textTag?.Trim(), StringComparison.InvariantCultureIgnoreCase))
Log.Error("Someone Logged In As GameBot");
} catch (Exception e)
{
Log.Error("XmppOnOnStreamError", e);
}
}

private void XmppOnOnAgentStart(object sender)
{
if (OnCheckRecieved != null)
OnCheckRecieved.Invoke(sender);
try
{
if (OnCheckRecieved != null)
OnCheckRecieved.Invoke(sender);
} catch (Exception e)
{
Log.Error("XmppOnOnAgentStart", e);
}
}

public void CheckBotStatus()
{
Xmpp.RequestAgents();
_xmpp.RequestAgents();
}

void Xmpp_OnAuthError(object sender, Element e)
@@ -169,9 +182,15 @@ private void XmppOnOnError(object sender, Exception exception)

private void XmppOnOnXmppConnectionStateChanged(object sender, XmppConnectionState state)
{
Log.InfoFormat("[Bot]Connection State Changed To {0}", state);
if (state == XmppConnectionState.Disconnected)
RemakeXmpp();
try
{
Log.InfoFormat("[Bot]Connection State Changed To {0}", state);
if (state == XmppConnectionState.Disconnected)
RemakeXmpp();
} catch (Exception e)
{
Log.Error("XmppOnOnXmppConnectionStateChanged", e);
}
}

private void XmppOnOnMessage(object sender, Message msg)
@@ -184,45 +203,51 @@ private void XmppOnOnMessage(object sender, Message msg)
if (msg.Subject == "hostgame")
{

if (msg.HasChildElements == false)
if (!msg.HasChildElements)
{
Log.Error("BADREQUEST hostgame has no children");
// F it, someone screwed up this year.
return;
}

if (msg.ChildNodes.OfType<HostGameRequest>().Any() == false)
if (!msg.ChildNodes.OfType<HostGameRequest>().Any())
{
Log.Error("BADREQUEST hostgame doesn't have a request");
// Again, what the fuuuuu
return;
}

var req = msg.ChildNodes.OfType<HostGameRequest>().First();

Log.InfoFormat("Host game from {0}", msg.From);
var endTime = DateTime.Now.AddSeconds(10);
while (SasUpdater.Instance.IsUpdating)
{
Thread.Sleep(100);
if (endTime > DateTime.Now) throw new Exception("Couldn't host, sas is updating");
}
var id = GameManager.Instance.HostGame(req, new User(msg.From));

if (id == Guid.Empty) throw new InvalidOperationException("id == Guid.Empty");

if (id != Guid.Empty)
userRequests.Add("hostrequest_" + id, id, DateTimeOffset.UtcNow.AddSeconds(30));
_userRequests.Add("hostrequest_" + id, id, DateTimeOffset.UtcNow.AddSeconds(30));
}
else if (msg.Subject == "gamelist")
{
// If someone tried to refresh their game list too soon, f them
if (userRequests.Contains("refreshrequest_" + msg.From.User.ToLower()))
if (_userRequests.Contains("refreshrequest_" + msg.From.User.ToLower()))
return;
// Mark the user as already requested a list for the next 15 seconds
userRequests.Add("refreshrequest_" + msg.From.User.ToLower(), 1, DateTimeOffset.UtcNow.AddSeconds(15));
_userRequests.Add("refreshrequest_" + msg.From.User.ToLower(), 1, DateTimeOffset.UtcNow.AddSeconds(15));
var list = GameManager.Instance.Games;
var m = new Message(msg.From, MessageType.normal, "", "gamelist");
m.GenerateId();
foreach (var a in list)
{
m.AddChild(a);
}
Xmpp.Send(m);
_xmpp.Send(m);
}
else if (msg.Subject == "killgame")
{
@@ -234,11 +259,11 @@ private void XmppOnOnMessage(object sender, Message msg)
{
var id = Guid.Parse(items[0]);
GameManager.Instance.KillGame(id);
}
throw new Exception("Error verifying user " + res);
} else throw new Exception("Error verifying user " + res);
}
break;
case MessageType.error:
Log.Error("Message Error " + msg.Error);
break;
case MessageType.chat:
if (!msg.From.User.Equals("d0c", StringComparison.InvariantCultureIgnoreCase)) return;
@@ -268,19 +293,20 @@ private void XmppOnOnMessage(object sender, Message msg)
/// </summary>
public void Dispose()
{
if (Xmpp != null)
Log.Info(nameof(GameBot) + " Disposed");
if (_xmpp != null)
{
Xmpp.OnMessage -= XmppOnOnMessage;
Xmpp.OnError -= XmppOnOnError;
Xmpp.OnAuthError -= Xmpp_OnAuthError;
Xmpp.OnStreamError -= XmppOnOnStreamError;
Xmpp.OnAgentStart -= XmppOnOnAgentStart;
Xmpp.OnXmppConnectionStateChanged -= XmppOnOnXmppConnectionStateChanged;
try { Xmpp.Close(); }
_xmpp.OnMessage -= XmppOnOnMessage;
_xmpp.OnError -= XmppOnOnError;
_xmpp.OnAuthError -= Xmpp_OnAuthError;
_xmpp.OnStreamError -= XmppOnOnStreamError;
_xmpp.OnAgentStart -= XmppOnOnAgentStart;
_xmpp.OnXmppConnectionStateChanged -= XmppOnOnXmppConnectionStateChanged;
try { _xmpp.Close(); }
catch { }
}
userRequests.Dispose();
refreshGamesTimer.Elapsed -= RefreshGamesTimerOnElapsed;
_userRequests.Dispose();
_refreshGamesTimer.Elapsed -= RefreshGamesTimerOnElapsed;
}

#endregion

0 comments on commit de75cfc

Please sign in to comment.
You can’t perform that action at this time.