Terraria 1.4.0.5 Source Code

This commit is contained in:
MikeyIsBaeYT 2021-10-26 12:45:26 -04:00
commit 05205f009e
1059 changed files with 563450 additions and 0 deletions

View file

@ -0,0 +1,173 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.AchievementsSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System;
using System.Threading;
namespace Terraria.Social.WeGame
{
public class AchievementsSocialModule : Terraria.Social.Base.AchievementsSocialModule
{
private const string FILE_NAME = "/achievements-wegame.dat";
private bool _areStatsReceived;
private bool _areAchievementReceived;
private RailCallBackHelper _callbackHelper = new RailCallBackHelper();
private IRailPlayerAchievement _playerAchievement;
private IRailPlayerStats _playerStats;
public override void Initialize()
{
// ISSUE: method pointer
this._callbackHelper.RegisterCallback((RAILEventID) 2001, new RailEventCallBackHandler((object) this, __methodptr(RailEventCallBack)));
// ISSUE: method pointer
this._callbackHelper.RegisterCallback((RAILEventID) 2101, new RailEventCallBackHandler((object) this, __methodptr(RailEventCallBack)));
IRailPlayerStats myPlayerStats = this.GetMyPlayerStats();
IRailPlayerAchievement playerAchievement = this.GetMyPlayerAchievement();
if (myPlayerStats == null || playerAchievement == null)
return;
myPlayerStats.AsyncRequestStats("");
playerAchievement.AsyncRequestAchievement("");
while (!this._areStatsReceived && !this._areAchievementReceived)
{
CoreSocialModule.RailEventTick();
Thread.Sleep(10);
}
}
public override void Shutdown() => this.StoreStats();
private IRailPlayerStats GetMyPlayerStats()
{
if (this._playerStats == null)
{
IRailStatisticHelper irailStatisticHelper = rail_api.RailFactory().RailStatisticHelper();
if (irailStatisticHelper != null)
{
RailID railId = new RailID();
((RailComparableID) railId).id_ = (__Null) 0L;
this._playerStats = irailStatisticHelper.CreatePlayerStats(railId);
}
}
return this._playerStats;
}
private IRailPlayerAchievement GetMyPlayerAchievement()
{
if (this._playerAchievement == null)
{
IRailAchievementHelper achievementHelper = rail_api.RailFactory().RailAchievementHelper();
if (achievementHelper != null)
{
RailID railId = new RailID();
((RailComparableID) railId).id_ = (__Null) 0L;
this._playerAchievement = achievementHelper.CreatePlayerAchievement(railId);
}
}
return this._playerAchievement;
}
public void RailEventCallBack(RAILEventID eventId, EventBase data)
{
if (eventId != 2001)
{
if (eventId != 2101)
return;
this._areAchievementReceived = true;
}
else
this._areStatsReceived = true;
}
public override bool IsAchievementCompleted(string name)
{
bool flag = false;
RailResult railResult = (RailResult) 1;
IRailPlayerAchievement playerAchievement = this.GetMyPlayerAchievement();
if (playerAchievement != null)
railResult = playerAchievement.HasAchieved(name, ref flag);
return flag && railResult == 0;
}
public override byte[] GetEncryptionKey()
{
RailID railId = rail_api.RailFactory().RailPlayer().GetRailID();
byte[] numArray = new byte[16];
byte[] bytes = BitConverter.GetBytes((ulong) ((RailComparableID) railId).id_);
Array.Copy((Array) bytes, (Array) numArray, 8);
Array.Copy((Array) bytes, 0, (Array) numArray, 8, 8);
return numArray;
}
public override string GetSavePath() => "/achievements-wegame.dat";
private int GetIntStat(string name)
{
int num = 0;
this.GetMyPlayerStats()?.GetStatValue(name, ref num);
return num;
}
private float GetFloatStat(string name)
{
double num = 0.0;
this.GetMyPlayerStats()?.GetStatValue(name, ref num);
return (float) num;
}
private bool SetFloatStat(string name, float value)
{
IRailPlayerStats myPlayerStats = this.GetMyPlayerStats();
RailResult railResult = (RailResult) 1;
if (myPlayerStats != null)
railResult = myPlayerStats.SetStatValue(name, (double) value);
return railResult == 0;
}
public override void UpdateIntStat(string name, int value)
{
IRailPlayerStats myPlayerStats = this.GetMyPlayerStats();
if (myPlayerStats == null)
return;
int num = 0;
if (myPlayerStats.GetStatValue(name, ref num) != null || num >= value)
return;
myPlayerStats.SetStatValue(name, value);
}
private bool SetIntStat(string name, int value)
{
IRailPlayerStats myPlayerStats = this.GetMyPlayerStats();
RailResult railResult = (RailResult) 1;
if (myPlayerStats != null)
railResult = myPlayerStats.SetStatValue(name, value);
return railResult == 0;
}
public override void UpdateFloatStat(string name, float value)
{
IRailPlayerStats myPlayerStats = this.GetMyPlayerStats();
if (myPlayerStats == null)
return;
double num = 0.0;
if (myPlayerStats.GetStatValue(name, ref num) != null || num >= (double) value)
return;
myPlayerStats.SetStatValue(name, (double) value);
}
public override void StoreStats()
{
this.SaveStats();
this.SaveAchievement();
}
private void SaveStats() => this.GetMyPlayerStats()?.AsyncStoreStats("");
private void SaveAchievement() => this.GetMyPlayerAchievement()?.AsyncStoreAchievement("");
public override void CompleteAchievement(string name) => this.GetMyPlayerAchievement()?.MakeAchievement(name);
}
}

View file

@ -0,0 +1,26 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.AsyncTaskHelper
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System;
using System.Threading.Tasks;
namespace Terraria.Social.WeGame
{
public class AsyncTaskHelper
{
private CurrentThreadRunner _currentThreadRunner;
private AsyncTaskHelper() => this._currentThreadRunner = new CurrentThreadRunner();
public void RunAsyncTaskAndReply(Action task, Action replay) => Task.Factory.StartNew((Action) (() =>
{
task();
this._currentThreadRunner.Run(replay);
}));
public void RunAsyncTask(Action task) => Task.Factory.StartNew(task);
}
}

View file

@ -0,0 +1,93 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.CloudSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System.Collections.Generic;
namespace Terraria.Social.WeGame
{
public class CloudSocialModule : Terraria.Social.Base.CloudSocialModule
{
private object ioLock = new object();
public override void Initialize() => base.Initialize();
public override void Shutdown()
{
}
public override IEnumerable<string> GetFiles()
{
lock (this.ioLock)
{
uint fileCount = rail_api.RailFactory().RailStorageHelper().GetFileCount();
List<string> stringList = new List<string>((int) fileCount);
ulong num = 0;
for (uint index = 0; index < fileCount; ++index)
{
string str;
rail_api.RailFactory().RailStorageHelper().GetFileNameAndSize(index, ref str, ref num);
stringList.Add(str);
}
return (IEnumerable<string>) stringList;
}
}
public override bool Write(string path, byte[] data, int length)
{
lock (this.ioLock)
{
bool flag = true;
IRailFile irailFile = !rail_api.RailFactory().RailStorageHelper().IsFileExist(path) ? rail_api.RailFactory().RailStorageHelper().CreateFile(path) : rail_api.RailFactory().RailStorageHelper().OpenFile(path);
if (irailFile != null)
{
int num = (int) irailFile.Write(data, (uint) length);
irailFile.Close();
}
else
flag = false;
return flag;
}
}
public override int GetFileSize(string path)
{
lock (this.ioLock)
{
IRailFile irailFile = rail_api.RailFactory().RailStorageHelper().OpenFile(path);
if (irailFile == null)
return 0;
int size = (int) irailFile.GetSize();
irailFile.Close();
return size;
}
}
public override void Read(string path, byte[] buffer, int size)
{
lock (this.ioLock)
{
IRailFile irailFile = rail_api.RailFactory().RailStorageHelper().OpenFile(path);
if (irailFile == null)
return;
int num = (int) irailFile.Read(buffer, (uint) size);
irailFile.Close();
}
}
public override bool HasFile(string path)
{
lock (this.ioLock)
return rail_api.RailFactory().RailStorageHelper().IsFileExist(path);
}
public override bool Delete(string path)
{
lock (this.ioLock)
return rail_api.RailFactory().RailStorageHelper().RemoveFile(path) == 0;
}
}
}

View file

@ -0,0 +1,87 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.CoreSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace Terraria.Social.WeGame
{
public class CoreSocialModule : ISocialModule
{
private RailCallBackHelper _callbackHelper = new RailCallBackHelper();
private static object _railTickLock = new object();
private bool isRailValid;
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
public static event Action OnTick;
public void Initialize()
{
RailGameID railGameId = new RailGameID();
((RailComparableID) railGameId).id_ = (__Null) 2000328L;
string[] strArray = new string[1]{ " " };
if (rail_api.RailNeedRestartAppForCheckingEnvironment(railGameId, strArray.Length, strArray))
Environment.Exit(1);
if (!rail_api.RailInitialize())
Environment.Exit(1);
// ISSUE: method pointer
this._callbackHelper.RegisterCallback((RAILEventID) 2, new RailEventCallBackHandler((object) null, __methodptr(RailEventCallBack)));
this.isRailValid = true;
ThreadPool.QueueUserWorkItem(new WaitCallback(this.TickThread), (object) null);
Main.OnTickForThirdPartySoftwareOnly += new Action(CoreSocialModule.RailEventTick);
}
public static void RailEventTick()
{
rail_api.RailFireEvents();
if (!Monitor.TryEnter(CoreSocialModule._railTickLock))
return;
Monitor.Pulse(CoreSocialModule._railTickLock);
Monitor.Exit(CoreSocialModule._railTickLock);
}
private void TickThread(object context)
{
Monitor.Enter(CoreSocialModule._railTickLock);
while (this.isRailValid)
{
if (CoreSocialModule.OnTick != null)
CoreSocialModule.OnTick();
Monitor.Wait(CoreSocialModule._railTickLock);
}
Monitor.Exit(CoreSocialModule._railTickLock);
}
public void Shutdown()
{
Application.ApplicationExit += (EventHandler) ((obj, evt) => this.isRailValid = false);
this._callbackHelper.UnregisterAllCallback();
rail_api.RailFinalize();
}
public static void RailEventCallBack(RAILEventID eventId, EventBase data)
{
if (eventId != 2)
return;
CoreSocialModule.ProcessRailSystemStateChange((RailSystemState) ((RailSystemStateChanged) data).state);
}
public static void SaveAndQuitCallBack() => Main.WeGameRequireExitGame();
private static void ProcessRailSystemStateChange(RailSystemState state)
{
if (state != 2 && state != 3)
return;
int num = (int) MessageBox.Show("检测到WeGame异常游戏将自动保存进度并退出游戏", "Terraria--WeGame Error");
WorldGen.SaveAndQuit(new Action(CoreSocialModule.SaveAndQuitCallBack));
}
}
}

View file

@ -0,0 +1,20 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.CurrentThreadRunner
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System;
using System.Windows.Threading;
namespace Terraria.Social.WeGame
{
public class CurrentThreadRunner
{
private Dispatcher _dsipatcher;
public CurrentThreadRunner() => this._dsipatcher = Dispatcher.CurrentDispatcher;
public void Run(Action f) => this._dsipatcher.BeginInvoke((Delegate) f);
}
}

View file

@ -0,0 +1,35 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.FriendsSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
namespace Terraria.Social.WeGame
{
public class FriendsSocialModule : Terraria.Social.Base.FriendsSocialModule
{
public override void Initialize()
{
}
public override void Shutdown()
{
}
public override string GetUsername()
{
string str;
rail_api.RailFactory().RailPlayer().GetPlayerName(ref str);
WeGameHelper.WriteDebugString("GetUsername by wegame" + str);
return str;
}
public override void OpenJoinInterface()
{
WeGameHelper.WriteDebugString("OpenJoinInterface by wegame");
rail_api.RailFactory().RailFloatingWindow().AsyncShowRailFloatingWindow((EnumRailWindowType) 10, "");
}
}
}

179
Social/WeGame/IPCBase.cs Normal file
View file

@ -0,0 +1,179 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.IPCBase
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
namespace Terraria.Social.WeGame
{
public abstract class IPCBase
{
private List<List<byte>> _producer = new List<List<byte>>();
private List<List<byte>> _consumer = new List<List<byte>>();
private List<byte> _totalData = new List<byte>();
private object _listLock = new object();
private volatile bool _haveDataToReadFlag;
protected volatile bool _pipeBrokenFlag;
protected PipeStream _pipeStream;
protected CancellationTokenSource _cancelTokenSrc;
protected Action<byte[]> _onDataArrive;
public int BufferSize { set; get; }
public virtual event Action<byte[]> OnDataArrive
{
add => this._onDataArrive += value;
remove => this._onDataArrive -= value;
}
public IPCBase() => this.BufferSize = 256;
protected void AddPackToList(List<byte> pack)
{
lock (this._listLock)
{
this._producer.Add(pack);
this._haveDataToReadFlag = true;
}
}
protected List<List<byte>> GetPackList()
{
List<List<byte>> byteListList = (List<List<byte>>) null;
lock (this._listLock)
{
List<List<byte>> producer = this._producer;
this._producer = this._consumer;
this._consumer = producer;
this._producer.Clear();
byteListList = this._consumer;
this._haveDataToReadFlag = false;
}
return byteListList;
}
protected bool HaveDataToRead() => this._haveDataToReadFlag;
public virtual void Reset()
{
this._cancelTokenSrc.Cancel();
this._pipeStream.Dispose();
this._pipeStream = (PipeStream) null;
}
public virtual void ProcessDataArriveEvent()
{
if (!this.HaveDataToRead())
return;
List<List<byte>> packList = this.GetPackList();
if (packList == null || this._onDataArrive == null)
return;
foreach (List<byte> byteList in packList)
this._onDataArrive(byteList.ToArray());
}
protected virtual bool BeginReadData()
{
bool flag = false;
IPCContent ipcContent = new IPCContent()
{
data = new byte[this.BufferSize],
CancelToken = this._cancelTokenSrc.Token
};
WeGameHelper.WriteDebugString(nameof (BeginReadData));
try
{
if (this._pipeStream != null)
{
this._pipeStream.BeginRead(ipcContent.data, 0, this.BufferSize, new AsyncCallback(this.ReadCallback), (object) ipcContent);
flag = true;
}
}
catch (IOException ex)
{
this._pipeBrokenFlag = true;
WeGameHelper.WriteDebugString("BeginReadData Exception, {0}", (object) ex.Message);
}
return flag;
}
public virtual void ReadCallback(IAsyncResult result)
{
WeGameHelper.WriteDebugString("ReadCallback: " + Thread.CurrentThread.ManagedThreadId.ToString());
IPCContent asyncState = (IPCContent) result.AsyncState;
try
{
int count = this._pipeStream.EndRead(result);
if (!asyncState.CancelToken.IsCancellationRequested)
{
if (count <= 0)
return;
this._totalData.AddRange(((IEnumerable<byte>) asyncState.data).Take<byte>(count));
if (!this._pipeStream.IsMessageComplete)
return;
this.AddPackToList(this._totalData);
this._totalData = new List<byte>();
}
else
WeGameHelper.WriteDebugString("IPCBase.ReadCallback.cancel");
}
catch (IOException ex)
{
this._pipeBrokenFlag = true;
WeGameHelper.WriteDebugString("ReadCallback Exception, {0}", (object) ex.Message);
}
catch (InvalidOperationException ex)
{
this._pipeBrokenFlag = true;
WeGameHelper.WriteDebugString("ReadCallback Exception, {0}", (object) ex.Message);
}
}
public virtual bool Send(string value) => this.Send(Encoding.UTF8.GetBytes(value));
public virtual bool Send(byte[] data)
{
bool flag = false;
if (this._pipeStream != null)
{
if (this._pipeStream.IsConnected)
{
try
{
this._pipeStream.BeginWrite(data, 0, data.Length, new AsyncCallback(this.SendCallback), (object) null);
flag = true;
}
catch (IOException ex)
{
this._pipeBrokenFlag = true;
WeGameHelper.WriteDebugString("Send Exception, {0}", (object) ex.Message);
}
}
}
return flag;
}
protected virtual void SendCallback(IAsyncResult result)
{
try
{
if (this._pipeStream == null)
return;
this._pipeStream.EndWrite(result);
}
catch (IOException ex)
{
this._pipeBrokenFlag = true;
WeGameHelper.WriteDebugString("SendCallback Exception, {0}", (object) ex.Message);
}
}
}
}

View file

@ -0,0 +1,89 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.IPCClient
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
namespace Terraria.Social.WeGame
{
public class IPCClient : IPCBase
{
private bool _connectedFlag;
public event Action OnConnected;
public override event Action<byte[]> OnDataArrive
{
add => this._onDataArrive = this._onDataArrive + value;
remove => this._onDataArrive = this._onDataArrive - value;
}
private NamedPipeClientStream GetPipeStream() => (NamedPipeClientStream) this._pipeStream;
private void ProcessConnectedEvent()
{
if (!this._connectedFlag)
return;
if (this.OnConnected != null)
this.OnConnected();
this._connectedFlag = false;
}
private void ProcessPipeBrokenEvent()
{
if (!this._pipeBrokenFlag)
return;
this.Reset();
this._pipeBrokenFlag = false;
}
private void CheckFlagAndFireEvent()
{
this.ProcessConnectedEvent();
this.ProcessDataArriveEvent();
this.ProcessPipeBrokenEvent();
}
public void Init(string clientName)
{
}
public void ConnectTo(string serverName)
{
if (this.GetPipeStream() != null)
return;
this._pipeStream = (PipeStream) new NamedPipeClientStream(".", serverName, PipeDirection.InOut, PipeOptions.Asynchronous);
this._cancelTokenSrc = new CancellationTokenSource();
Task.Factory.StartNew((Action<object>) (content =>
{
this.GetPipeStream().Connect();
if (((CancellationToken) content).IsCancellationRequested)
return;
this.GetPipeStream().ReadMode = PipeTransmissionMode.Message;
this.BeginReadData();
this._connectedFlag = true;
}), (object) this._cancelTokenSrc.Token);
}
public void Tick() => this.CheckFlagAndFireEvent();
public override void ReadCallback(IAsyncResult result)
{
IPCContent asyncState = (IPCContent) result.AsyncState;
base.ReadCallback(result);
if (!asyncState.CancelToken.IsCancellationRequested)
{
if (!this.GetPipeStream().IsConnected)
return;
this.BeginReadData();
}
else
WeGameHelper.WriteDebugString("ReadCallback cancel");
}
}
}

View file

@ -0,0 +1,17 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.IPCContent
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System.Threading;
namespace Terraria.Social.WeGame
{
public class IPCContent
{
public byte[] data;
public CancellationToken CancelToken { get; set; }
}
}

View file

@ -0,0 +1,45 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.IPCMessage
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Terraria.Social.WeGame
{
public class IPCMessage
{
private IPCMessageType _cmd;
private string _jsonData;
public void Build<T>(IPCMessageType cmd, T t)
{
this._jsonData = WeGameHelper.Serialize<T>(t);
this._cmd = cmd;
}
public void BuildFrom(byte[] data)
{
byte[] array1 = ((IEnumerable<byte>) data).Take<byte>(4).ToArray<byte>();
byte[] array2 = ((IEnumerable<byte>) data).Skip<byte>(4).ToArray<byte>();
this._cmd = (IPCMessageType) BitConverter.ToInt32(array1, 0);
this._jsonData = Encoding.UTF8.GetString(array2);
}
public void Parse<T>(out T value) => WeGameHelper.UnSerialize<T>(this._jsonData, out value);
public byte[] GetBytes()
{
List<byte> byteList = new List<byte>();
byteList.AddRange((IEnumerable<byte>) BitConverter.GetBytes((int) this._cmd));
byteList.AddRange((IEnumerable<byte>) Encoding.UTF8.GetBytes(this._jsonData));
return byteList.ToArray();
}
public IPCMessageType GetCmd() => this._cmd;
}
}

View file

@ -0,0 +1,14 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.IPCMessageType
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
namespace Terraria.Social.WeGame
{
public enum IPCMessageType
{
IPCMessageTypeReportServerID,
IPCMessageTypeNotifyFriendList,
}
}

124
Social/WeGame/IPCServer.cs Normal file
View file

@ -0,0 +1,124 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.IPCServer
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;
namespace Terraria.Social.WeGame
{
public class IPCServer : IPCBase
{
private string _serverName;
private bool _haveClientAccessFlag;
public event Action OnClientAccess;
public override event Action<byte[]> OnDataArrive
{
add => this._onDataArrive = this._onDataArrive + value;
remove => this._onDataArrive = this._onDataArrive - value;
}
private NamedPipeServerStream GetPipeStream() => (NamedPipeServerStream) this._pipeStream;
public void Init(string serverName) => this._serverName = serverName;
private void LazyCreatePipe()
{
if (this.GetPipeStream() != null)
return;
this._pipeStream = (PipeStream) new NamedPipeServerStream(this._serverName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
this._cancelTokenSrc = new CancellationTokenSource();
}
public override void ReadCallback(IAsyncResult result)
{
IPCContent asyncState = (IPCContent) result.AsyncState;
base.ReadCallback(result);
if (!asyncState.CancelToken.IsCancellationRequested)
this.ContinueReadOrWait();
else
WeGameHelper.WriteDebugString("servcer.ReadCallback cancel");
}
public void StartListen()
{
this.LazyCreatePipe();
WeGameHelper.WriteDebugString("begin listen");
this.GetPipeStream().BeginWaitForConnection(new AsyncCallback(this.ConnectionCallback), (object) this._cancelTokenSrc.Token);
}
private void RestartListen() => this.StartListen();
private void ConnectionCallback(IAsyncResult result)
{
try
{
this._haveClientAccessFlag = true;
WeGameHelper.WriteDebugString("Connected in");
this.GetPipeStream().EndWaitForConnection(result);
if (!((CancellationToken) result.AsyncState).IsCancellationRequested)
this.BeginReadData();
else
WeGameHelper.WriteDebugString("ConnectionCallback but user cancel");
}
catch (IOException ex)
{
this._pipeBrokenFlag = true;
WeGameHelper.WriteDebugString("ConnectionCallback Exception, {0}", (object) ex.Message);
}
}
public void ContinueReadOrWait()
{
if (this.GetPipeStream().IsConnected)
{
this.BeginReadData();
}
else
{
try
{
this.GetPipeStream().BeginWaitForConnection(new AsyncCallback(this.ConnectionCallback), (object) null);
}
catch (IOException ex)
{
this._pipeBrokenFlag = true;
WeGameHelper.WriteDebugString("ContinueReadOrWait Exception, {0}", (object) ex.Message);
}
}
}
private void ProcessClientAccessEvent()
{
if (!this._haveClientAccessFlag)
return;
if (this.OnClientAccess != null)
this.OnClientAccess();
this._haveClientAccessFlag = false;
}
private void CheckFlagAndFireEvent()
{
this.ProcessClientAccessEvent();
this.ProcessDataArriveEvent();
this.ProcessPipeBrokenEvent();
}
private void ProcessPipeBrokenEvent()
{
if (!this._pipeBrokenFlag)
return;
this.Reset();
this._pipeBrokenFlag = false;
this.RestartListen();
}
public void Tick() => this.CheckFlagAndFireEvent();
}
}

102
Social/WeGame/Lobby.cs Normal file
View file

@ -0,0 +1,102 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.Lobby
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System;
namespace Terraria.Social.WeGame
{
public class Lobby
{
private RailCallBackHelper _callbackHelper = new RailCallBackHelper();
public LobbyState State;
private bool _gameServerInitSuccess;
private IRailGameServer _gameServer;
public Action<RailID> _lobbyCreatedExternalCallback;
private RailID _server_id;
private IRailGameServer RailServerHelper
{
get => this._gameServerInitSuccess ? this._gameServer : (IRailGameServer) null;
set => this._gameServer = value;
}
private IRailGameServerHelper GetRailServerHelper() => rail_api.RailFactory().RailGameServerHelper();
private void RegisterGameServerEvent()
{
if (this._callbackHelper == null)
return;
// ISSUE: method pointer
this._callbackHelper.RegisterCallback((RAILEventID) 3002, new RailEventCallBackHandler((object) this, __methodptr(OnRailEvent)));
}
public void OnRailEvent(RAILEventID id, EventBase data)
{
WeGameHelper.WriteDebugString("OnRailEvent,id=" + id.ToString() + " ,result=" + data.result.ToString());
if (id != 3002)
return;
this.OnGameServerCreated((CreateGameServerResult) data);
}
private void OnGameServerCreated(CreateGameServerResult result)
{
if (((EventBase) result).result != null)
return;
this._gameServerInitSuccess = true;
this._lobbyCreatedExternalCallback((RailID) result.game_server_id);
this._server_id = (RailID) result.game_server_id;
}
public void Create(bool inviteOnly)
{
if (this.State == LobbyState.Inactive)
this.RegisterGameServerEvent();
this.RailServerHelper = rail_api.RailFactory().RailGameServerHelper().AsyncCreateGameServer(new CreateGameServerOptions()
{
has_password = (__Null) 0,
enable_team_voice = (__Null) 0
}, "terraria", "terraria");
this.State = LobbyState.Creating;
}
public void OpenInviteOverlay()
{
WeGameHelper.WriteDebugString("OpenInviteOverlay by wegame");
rail_api.RailFactory().RailFloatingWindow().AsyncShowRailFloatingWindow((EnumRailWindowType) 10, "");
}
public void Join(RailID local_peer, RailID remote_peer)
{
if (this.State != LobbyState.Inactive)
WeGameHelper.WriteDebugString("Lobby connection attempted while already in a lobby. This should never happen?");
else
this.State = LobbyState.Connecting;
}
public byte[] GetMessage(int index) => (byte[]) null;
public int GetUserCount() => 0;
public RailID GetUserByIndex(int index) => (RailID) null;
public bool SendMessage(byte[] data) => this.SendMessage(data, data.Length);
public bool SendMessage(byte[] data, int length) => false;
public void Set(RailID lobbyId)
{
}
public void SetPlayedWith(RailID userId)
{
}
public void Leave() => this.State = LobbyState.Inactive;
public IRailGameServer GetServer() => this.RailServerHelper;
}
}

View file

@ -0,0 +1,16 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.LobbyState
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
namespace Terraria.Social.WeGame
{
public enum LobbyState
{
Inactive,
Connecting,
Creating,
Active,
}
}

View file

@ -0,0 +1,12 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.MessageDispatcherBase
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
namespace Terraria.Social.WeGame
{
public abstract class MessageDispatcherBase
{
}
}

View file

@ -0,0 +1,52 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.MessageDispatcherClient
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System;
namespace Terraria.Social.WeGame
{
public class MessageDispatcherClient
{
private IPCClient _ipcClient = new IPCClient();
private string _severName;
private string _clientName;
public event Action<IPCMessage> OnMessage;
public event Action OnConnected;
public void Init(string clientName, string serverName)
{
this._clientName = clientName;
this._severName = serverName;
this._ipcClient.Init(clientName);
this._ipcClient.OnDataArrive += new Action<byte[]>(this.OnDataArrive);
this._ipcClient.OnConnected += new Action(this.OnServerConnected);
}
public void Start() => this._ipcClient.ConnectTo(this._severName);
private void OnDataArrive(byte[] data)
{
IPCMessage ipcMessage = new IPCMessage();
ipcMessage.BuildFrom(data);
if (this.OnMessage == null)
return;
this.OnMessage(ipcMessage);
}
private void OnServerConnected()
{
if (this.OnConnected == null)
return;
this.OnConnected();
}
public void Tick() => this._ipcClient.Tick();
public bool SendMessage(IPCMessage msg) => this._ipcClient.Send(msg.GetBytes());
}
}

View file

@ -0,0 +1,48 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.MessageDispatcherServer
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System;
namespace Terraria.Social.WeGame
{
public class MessageDispatcherServer
{
private IPCServer _ipcSever = new IPCServer();
public event Action OnIPCClientAccess;
public event Action<IPCMessage> OnMessage;
public void Init(string serverName)
{
this._ipcSever.Init(serverName);
this._ipcSever.OnDataArrive += new Action<byte[]>(this.OnDataArrive);
this._ipcSever.OnClientAccess += new Action(this.OnClientAccess);
}
public void OnClientAccess()
{
if (this.OnIPCClientAccess == null)
return;
this.OnIPCClientAccess();
}
public void Start() => this._ipcSever.StartListen();
private void OnDataArrive(byte[] data)
{
IPCMessage ipcMessage = new IPCMessage();
ipcMessage.BuildFrom(data);
if (this.OnMessage == null)
return;
this.OnMessage(ipcMessage);
}
public void Tick() => this._ipcSever.Tick();
public bool SendMessage(IPCMessage msg) => this._ipcSever.Send(msg.GetBytes());
}
}

View file

@ -0,0 +1,498 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.NetClientSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Terraria.Localization;
using Terraria.Net;
using Terraria.Net.Sockets;
namespace Terraria.Social.WeGame
{
public class NetClientSocialModule : NetSocialModule
{
private RailCallBackHelper _callbackHelper = new RailCallBackHelper();
private bool _hasLocalHost;
private IPCServer server = new IPCServer();
private readonly string _serverIDMedataKey = "terraria.serverid";
private RailID _inviter_id = new RailID();
private List<PlayerPersonalInfo> _player_info_list;
private MessageDispatcherServer _msgServer;
private void OnIPCClientAccess()
{
WeGameHelper.WriteDebugString("IPC client access");
this.SendFriendListToLocalServer();
}
private void LazyCreateWeGameMsgServer()
{
if (this._msgServer != null)
return;
this._msgServer = new MessageDispatcherServer();
this._msgServer.Init("WeGame.Terraria.Message.Server");
this._msgServer.OnMessage += new Action<IPCMessage>(this.OnWegameMessage);
this._msgServer.OnIPCClientAccess += new Action(this.OnIPCClientAccess);
CoreSocialModule.OnTick += new Action(this._msgServer.Tick);
this._msgServer.Start();
}
private void OnWegameMessage(IPCMessage message)
{
if (message.GetCmd() != IPCMessageType.IPCMessageTypeReportServerID)
return;
ReportServerID reportServerID;
message.Parse<ReportServerID>(out reportServerID);
this.OnReportServerID(reportServerID);
}
private void OnReportServerID(ReportServerID reportServerID)
{
WeGameHelper.WriteDebugString("OnReportServerID - " + reportServerID._serverID);
this.AsyncSetMyMetaData(this._serverIDMedataKey, reportServerID._serverID);
this.AsyncSetInviteCommandLine(reportServerID._serverID);
}
public override void Initialize()
{
base.Initialize();
this.RegisterRailEvent();
this.AsyncGetFriendsInfo();
this._reader.SetReadEvent(new WeGameP2PReader.OnReadEvent(this.OnPacketRead));
this._reader.SetLocalPeer(this.GetLocalPeer());
this._writer.SetLocalPeer(this.GetLocalPeer());
Main.OnEngineLoad += new Action(this.CheckParameters);
}
private void AsyncSetInviteCommandLine(string cmdline) => rail_api.RailFactory().RailFriends().AsyncSetInviteCommandLine(cmdline, "");
private void AsyncSetMyMetaData(string key, string value)
{
List<RailKeyValue> railKeyValueList = new List<RailKeyValue>();
railKeyValueList.Add(new RailKeyValue()
{
key = (__Null) key,
value = (__Null) value
});
rail_api.RailFactory().RailFriends().AsyncSetMyMetadata(railKeyValueList, "");
}
private bool TryAuthUserByRecvData(RailID user, byte[] data, int length)
{
WeGameHelper.WriteDebugString("TryAuthUserByRecvData user:{0}", (object) (ulong) ((RailComparableID) user).id_);
if (length < 3)
{
WeGameHelper.WriteDebugString("Failed to validate authentication packet: Too short. (Length: " + (object) length + ")");
return false;
}
int num = (int) data[1] << 8 | (int) data[0];
if (num != length)
{
WeGameHelper.WriteDebugString("Failed to validate authentication packet: Packet size mismatch. (" + (object) num + "!=" + (object) length + ")");
return false;
}
if (data[2] == (byte) 93)
return true;
WeGameHelper.WriteDebugString("Failed to validate authentication packet: Packet type is not correct. (Type: " + (object) data[2] + ")");
return false;
}
private bool OnPacketRead(byte[] data, int size, RailID user)
{
if (!this._connectionStateMap.ContainsKey(user))
return false;
NetSocialModule.ConnectionState connectionState = this._connectionStateMap[user];
if (connectionState != NetSocialModule.ConnectionState.Authenticating)
return connectionState == NetSocialModule.ConnectionState.Connected;
if (!this.TryAuthUserByRecvData(user, data, size))
{
WeGameHelper.WriteDebugString(" Auth Server Ticket Failed");
this.Close(user);
}
else
{
WeGameHelper.WriteDebugString("OnRailAuthSessionTicket Auth Success..");
this.OnAuthSuccess(user);
}
return false;
}
private void OnAuthSuccess(RailID remote_peer)
{
if (!this._connectionStateMap.ContainsKey(remote_peer))
return;
this._connectionStateMap[remote_peer] = NetSocialModule.ConnectionState.Connected;
this.AsyncSetPlayWith(this._inviter_id);
this.AsyncSetMyMetaData("status", Language.GetTextValue("Social.StatusInGame"));
// ISSUE: explicit non-virtual call
this.AsyncSetMyMetaData(this._serverIDMedataKey, __nonvirtual (((RailComparableID) remote_peer).id_.ToString()));
Main.clrInput();
Netplay.ServerPassword = "";
Main.GetInputText("");
Main.autoPass = false;
Main.netMode = 1;
Netplay.OnConnectedToSocialServer((ISocket) new SocialSocket((RemoteAddress) new WeGameAddress(remote_peer, this.GetFriendNickname(this._inviter_id))));
// ISSUE: explicit non-virtual call
WeGameHelper.WriteDebugString("OnConnectToSocialServer server:" + __nonvirtual (((RailComparableID) remote_peer).id_.ToString()));
}
private bool GetRailConnectIDFromCmdLine(RailID server_id)
{
foreach (string commandLineArg in Environment.GetCommandLineArgs())
{
string str = "--rail_connect_cmd=";
int num = commandLineArg.IndexOf(str);
if (num != -1)
{
ulong result = 0;
if (ulong.TryParse(commandLineArg.Substring(num + str.Length), out result))
{
((RailComparableID) server_id).id_ = (__Null) (long) result;
return true;
}
}
}
return false;
}
private void CheckParameters()
{
RailID server_id = new RailID();
if (!this.GetRailConnectIDFromCmdLine(server_id))
return;
if (((RailComparableID) server_id).IsValid())
Main.OpenPlayerSelect((Main.OnPlayerSelected) (playerData =>
{
Main.ServerSideCharacter = false;
playerData.SetAsActive();
Main.menuMode = 882;
Main.statusText = Language.GetTextValue("Social.Joining");
WeGameHelper.WriteDebugString(" CheckParameters lobby.join");
this.JoinServer(server_id);
}));
else
WeGameHelper.WriteDebugString("Invalid RailID passed to +connect_lobby");
}
public override void LaunchLocalServer(Process process, ServerMode mode)
{
if (this._lobby.State != LobbyState.Inactive)
this._lobby.Leave();
this.LazyCreateWeGameMsgServer();
ProcessStartInfo startInfo1 = process.StartInfo;
startInfo1.Arguments = startInfo1.Arguments + " -wegame -localwegameid " + (object) (ulong) ((RailComparableID) this.GetLocalPeer()).id_;
if (mode.HasFlag((Enum) ServerMode.Lobby))
{
this._hasLocalHost = true;
if (mode.HasFlag((Enum) ServerMode.FriendsCanJoin))
process.StartInfo.Arguments += " -lobby friends";
else
process.StartInfo.Arguments += " -lobby private";
if (mode.HasFlag((Enum) ServerMode.FriendsOfFriends))
process.StartInfo.Arguments += " -friendsoffriends";
}
string str;
rail_api.RailFactory().RailUtils().GetLaunchAppParameters((EnumRailLaunchAppType) 2, ref str);
ProcessStartInfo startInfo2 = process.StartInfo;
startInfo2.Arguments = startInfo2.Arguments + " " + str;
WeGameHelper.WriteDebugString("LaunchLocalServer,cmd_line:" + process.StartInfo.Arguments);
this.AsyncSetMyMetaData("status", Language.GetTextValue("Social.StatusInGame"));
Netplay.OnDisconnect += new Action(this.OnDisconnect);
process.Start();
}
public override void Shutdown()
{
this.AsyncSetInviteCommandLine("");
this.CleanMyMetaData();
this.UnRegisterRailEvent();
base.Shutdown();
}
public override ulong GetLobbyId() => 0;
public override bool StartListening(SocketConnectionAccepted callback) => false;
public override void StopListening()
{
}
public override void Close(RemoteAddress address)
{
this.CleanMyMetaData();
this.Close(this.RemoteAddressToRailId(address));
}
public override bool CanInvite() => (this._hasLocalHost || this._lobby.State == LobbyState.Active || Main.LobbyId != 0UL) && (uint) Main.netMode > 0U;
public override void OpenInviteInterface() => this._lobby.OpenInviteOverlay();
private void Close(RailID remote_peer)
{
if (!this._connectionStateMap.ContainsKey(remote_peer))
return;
WeGameHelper.WriteDebugString("CloseRemotePeer, remote:{0}", (object) (ulong) ((RailComparableID) remote_peer).id_);
rail_api.RailFactory().RailNetworkHelper().CloseSession(this.GetLocalPeer(), remote_peer);
this._connectionStateMap[remote_peer] = NetSocialModule.ConnectionState.Inactive;
this._lobby.Leave();
this._reader.ClearUser(remote_peer);
this._writer.ClearUser(remote_peer);
}
public override void Connect(RemoteAddress address)
{
}
public override void CancelJoin()
{
if (this._lobby.State == LobbyState.Inactive)
return;
this._lobby.Leave();
}
private void RegisterRailEvent()
{
RAILEventID[] railEventIdArray = new RAILEventID[7]
{
(RAILEventID) 16001,
(RAILEventID) 16002,
(RAILEventID) 13503,
(RAILEventID) 13501,
(RAILEventID) 12003,
(RAILEventID) 12002,
(RAILEventID) 12010
};
foreach (int num in railEventIdArray)
{
// ISSUE: method pointer
this._callbackHelper.RegisterCallback((RAILEventID) num, new RailEventCallBackHandler((object) this, __methodptr(OnRailEvent)));
}
}
private void UnRegisterRailEvent() => this._callbackHelper.UnregisterAllCallback();
public void OnRailEvent(RAILEventID id, EventBase data)
{
WeGameHelper.WriteDebugString("OnRailEvent,id=" + id.ToString() + " ,result=" + data.result.ToString());
if (id <= 12010)
{
if (id != 12002)
{
if (id != 12003)
{
if (id != 12010)
return;
this.OnFriendlistChange((RailFriendsListChanged) data);
}
else
this.OnGetFriendMetaData((RailFriendsGetMetadataResult) data);
}
else
this.OnRailSetMetaData((RailFriendsSetMetadataResult) data);
}
else if (id <= 13503)
{
if (id != 13501)
{
if (id != 13503)
return;
this.OnRailRespondInvation((RailUsersRespondInvitation) data);
}
else
this.OnRailGetUsersInfo((RailUsersInfoData) data);
}
else if (id != 16001)
{
if (id != 16002)
return;
this.OnRailCreateSessionFailed((CreateSessionFailed) data);
}
else
this.OnRailCreateSessionRequest((CreateSessionRequest) data);
}
private string DumpMataDataString(List<RailKeyValueResult> list)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (RailKeyValueResult railKeyValueResult in list)
stringBuilder.Append("key: " + (string) railKeyValueResult.key + " value: " + (string) railKeyValueResult.value);
return stringBuilder.ToString();
}
private string GetValueByKey(string key, List<RailKeyValueResult> list)
{
string str = (string) null;
foreach (RailKeyValueResult railKeyValueResult in list)
{
if ((string) railKeyValueResult.key == key)
{
str = (string) railKeyValueResult.value;
break;
}
}
return str;
}
private bool SendFriendListToLocalServer()
{
bool flag = false;
if (this._hasLocalHost)
{
List<RailFriendInfo> list = new List<RailFriendInfo>();
if (this.GetRailFriendList(list))
{
WeGameFriendListInfo t = new WeGameFriendListInfo()
{
_friendList = list
};
IPCMessage msg = new IPCMessage();
msg.Build<WeGameFriendListInfo>(IPCMessageType.IPCMessageTypeNotifyFriendList, t);
flag = this._msgServer.SendMessage(msg);
WeGameHelper.WriteDebugString("NotifyFriendListToServer: " + flag.ToString());
}
}
return flag;
}
private bool GetRailFriendList(List<RailFriendInfo> list)
{
bool flag = false;
IRailFriends irailFriends = rail_api.RailFactory().RailFriends();
if (irailFriends != null)
flag = irailFriends.GetFriendsList(list) == 0;
return flag;
}
private void OnGetFriendMetaData(RailFriendsGetMetadataResult data)
{
if (((EventBase) data).result != null || ((List<RailKeyValueResult>) data.friend_kvs).Count <= 0)
return;
WeGameHelper.WriteDebugString("OnGetFriendMetaData - " + this.DumpMataDataString((List<RailKeyValueResult>) data.friend_kvs));
string valueByKey = this.GetValueByKey(this._serverIDMedataKey, (List<RailKeyValueResult>) data.friend_kvs);
if (valueByKey == null)
return;
if (valueByKey.Length > 0)
{
RailID server_id = new RailID();
((RailComparableID) server_id).id_ = (__Null) (long) ulong.Parse(valueByKey);
if (((RailComparableID) server_id).IsValid())
this.JoinServer(server_id);
else
WeGameHelper.WriteDebugString("JoinServer failed, invalid server id");
}
else
WeGameHelper.WriteDebugString("can not find server id key");
}
private void JoinServer(RailID server_id)
{
WeGameHelper.WriteDebugString("JoinServer:{0}", (object) (ulong) ((RailComparableID) server_id).id_);
this._connectionStateMap[server_id] = NetSocialModule.ConnectionState.Authenticating;
int length = 3;
byte[] numArray = new byte[length];
numArray[0] = (byte) (length & (int) byte.MaxValue);
numArray[1] = (byte) (length >> 8 & (int) byte.MaxValue);
numArray[2] = (byte) 93;
rail_api.RailFactory().RailNetworkHelper().SendReliableData(this.GetLocalPeer(), server_id, numArray, (uint) length);
}
private string GetFriendNickname(RailID rail_id)
{
if (this._player_info_list != null)
{
foreach (PlayerPersonalInfo playerInfo in this._player_info_list)
{
if (RailComparableID.op_Equality((RailComparableID) playerInfo.rail_id, (RailComparableID) rail_id))
return (string) playerInfo.rail_name;
}
}
return "";
}
private void OnRailGetUsersInfo(RailUsersInfoData data) => this._player_info_list = (List<PlayerPersonalInfo>) data.user_info_list;
private void OnFriendlistChange(RailFriendsListChanged data)
{
if (!this._hasLocalHost)
return;
this.SendFriendListToLocalServer();
}
private void AsyncGetFriendsInfo()
{
IRailFriends irailFriends = rail_api.RailFactory().RailFriends();
if (irailFriends == null)
return;
List<RailFriendInfo> railFriendInfoList = new List<RailFriendInfo>();
irailFriends.GetFriendsList(railFriendInfoList);
List<RailID> railIdList = new List<RailID>();
foreach (RailFriendInfo railFriendInfo in railFriendInfoList)
railIdList.Add((RailID) railFriendInfo.friend_rail_id);
irailFriends.AsyncGetPersonalInfo(railIdList, "");
}
private void AsyncSetPlayWith(RailID rail_id)
{
List<RailUserPlayedWith> railUserPlayedWithList = new List<RailUserPlayedWith>();
railUserPlayedWithList.Add(new RailUserPlayedWith()
{
rail_id = (__Null) rail_id
});
rail_api.RailFactory().RailFriends()?.AsyncReportPlayedWithUserList(railUserPlayedWithList, "");
}
private void OnRailSetMetaData(RailFriendsSetMetadataResult data) => WeGameHelper.WriteDebugString("OnRailSetMetaData - " + ((EventBase) data).result.ToString());
private void OnRailRespondInvation(RailUsersRespondInvitation data)
{
WeGameHelper.WriteDebugString(" request join game");
if (this._lobby.State != LobbyState.Inactive)
this._lobby.Leave();
this._inviter_id = (RailID) data.inviter_id;
Main.OpenPlayerSelect((Main.OnPlayerSelected) (playerData =>
{
Main.ServerSideCharacter = false;
playerData.SetAsActive();
Main.menuMode = 882;
Main.statusText = Language.GetTextValue("Social.JoiningFriend", (object) this.GetFriendNickname((RailID) data.inviter_id));
this.AsyncGetServerIDByOwener((RailID) data.inviter_id);
WeGameHelper.WriteDebugString("inviter_id: " + (object) (ulong) ((RailComparableID) data.inviter_id).id_);
}));
}
private void AsyncGetServerIDByOwener(RailID ownerID) => rail_api.RailFactory().RailFriends()?.AsyncGetFriendMetadata(ownerID, new List<string>()
{
this._serverIDMedataKey
}, "");
private void OnRailCreateSessionRequest(CreateSessionRequest result)
{
WeGameHelper.WriteDebugString(nameof (OnRailCreateSessionRequest));
if (!this._connectionStateMap.ContainsKey((RailID) result.remote_peer) || this._connectionStateMap[(RailID) result.remote_peer] == NetSocialModule.ConnectionState.Inactive)
return;
WeGameHelper.WriteDebugString("AcceptSessionRequest, local{0}, remote:{1}", (object) (ulong) ((RailComparableID) result.local_peer).id_, (object) (ulong) ((RailComparableID) result.remote_peer).id_);
rail_api.RailFactory().RailNetworkHelper().AcceptSessionRequest((RailID) result.local_peer, (RailID) result.remote_peer);
}
private void OnRailCreateSessionFailed(CreateSessionFailed result)
{
WeGameHelper.WriteDebugString("OnRailCreateSessionFailed, CloseRemote: local:{0}, remote:{1}", (object) (ulong) ((RailComparableID) result.local_peer).id_, (object) (ulong) ((RailComparableID) result.remote_peer).id_);
this.Close((RailID) result.remote_peer);
}
private void CleanMyMetaData() => rail_api.RailFactory().RailFriends()?.AsyncClearAllMyMetadata("");
private void OnDisconnect()
{
this.CleanMyMetaData();
this._hasLocalHost = false;
Netplay.OnDisconnect -= new Action(this.OnDisconnect);
}
}
}

View file

@ -0,0 +1,358 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.NetServerSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Terraria.Localization;
using Terraria.Net;
using Terraria.Net.Sockets;
namespace Terraria.Social.WeGame
{
public class NetServerSocialModule : NetSocialModule
{
private SocketConnectionAccepted _connectionAcceptedCallback;
private bool _acceptingClients;
private ServerMode _mode;
private RailCallBackHelper _callbackHelper = new RailCallBackHelper();
private MessageDispatcherClient _client = new MessageDispatcherClient();
private bool _serverConnected;
private RailID _serverID = new RailID();
private Action _ipcConnetedAction;
private List<RailFriendInfo> _wegameFriendList;
public NetServerSocialModule() => this._lobby._lobbyCreatedExternalCallback = new Action<RailID>(this.OnLobbyCreated);
private void BroadcastConnectedUsers()
{
}
private bool AcceptAnUserSession(RailID local_peer, RailID remote_peer)
{
bool flag = false;
// ISSUE: explicit non-virtual call
// ISSUE: explicit non-virtual call
WeGameHelper.WriteDebugString("AcceptAnUserSession server:" + __nonvirtual (((RailComparableID) local_peer).id_.ToString()) + " remote:" + __nonvirtual (((RailComparableID) remote_peer).id_.ToString()));
IRailNetwork irailNetwork = rail_api.RailFactory().RailNetworkHelper();
if (irailNetwork != null)
flag = irailNetwork.AcceptSessionRequest(local_peer, remote_peer) == 0;
return flag;
}
private void TerminateRemotePlayerSession(RailID remote_id) => rail_api.RailFactory().RailPlayer()?.TerminateSessionOfPlayer(remote_id);
private bool CloseNetWorkSession(RailID remote_peer)
{
bool flag = false;
IRailNetwork irailNetwork = rail_api.RailFactory().RailNetworkHelper();
if (irailNetwork != null)
flag = irailNetwork.CloseSession(this._serverID, remote_peer) == 0;
return flag;
}
private RailID GetServerID()
{
RailID railId = (RailID) null;
IRailGameServer server = this._lobby.GetServer();
if (server != null)
railId = server.GetGameServerRailID();
return railId ?? new RailID();
}
private void CloseAndUpdateUserState(RailID remote_peer)
{
if (!this._connectionStateMap.ContainsKey(remote_peer))
return;
WeGameHelper.WriteDebugString("CloseAndUpdateUserState, remote:{0}", (object) (ulong) ((RailComparableID) remote_peer).id_);
this.TerminateRemotePlayerSession(remote_peer);
this.CloseNetWorkSession(remote_peer);
this._connectionStateMap[remote_peer] = NetSocialModule.ConnectionState.Inactive;
this._reader.ClearUser(remote_peer);
this._writer.ClearUser(remote_peer);
}
public void OnConnected()
{
this._serverConnected = true;
if (this._ipcConnetedAction != null)
this._ipcConnetedAction();
this._ipcConnetedAction = (Action) null;
WeGameHelper.WriteDebugString("IPC connected");
}
private void OnCreateSessionRequest(CreateSessionRequest data)
{
if (!this._acceptingClients)
WeGameHelper.WriteDebugString(" - Ignoring connection from " + (object) (ulong) ((RailComparableID) data.remote_peer).id_ + " while _acceptionClients is false.");
else if (!this._mode.HasFlag((Enum) ServerMode.FriendsOfFriends) && !this.IsWeGameFriend((RailID) data.remote_peer))
{
WeGameHelper.WriteDebugString("Ignoring connection from " + (object) (ulong) ((RailComparableID) data.remote_peer).id_ + ". Friends of friends is disabled.");
}
else
{
WeGameHelper.WriteDebugString("pass wegame friend check");
this.AcceptAnUserSession((RailID) data.local_peer, (RailID) data.remote_peer);
this._connectionStateMap[(RailID) data.remote_peer] = NetSocialModule.ConnectionState.Authenticating;
if (this._connectionAcceptedCallback == null)
return;
this._connectionAcceptedCallback((ISocket) new SocialSocket((RemoteAddress) new WeGameAddress((RailID) data.remote_peer, "")));
}
}
private void OnCreateSessionFailed(CreateSessionFailed data)
{
WeGameHelper.WriteDebugString("CreateSessionFailed, local:{0}, remote:{1}", (object) (ulong) ((RailComparableID) data.local_peer).id_, (object) (ulong) ((RailComparableID) data.remote_peer).id_);
this.CloseAndUpdateUserState((RailID) data.remote_peer);
}
private bool GetRailFriendList(List<RailFriendInfo> list)
{
bool flag = false;
IRailFriends irailFriends = rail_api.RailFactory().RailFriends();
if (irailFriends != null)
flag = irailFriends.GetFriendsList(list) == 0;
return flag;
}
private void OnWegameMessage(IPCMessage message)
{
if (message.GetCmd() != IPCMessageType.IPCMessageTypeNotifyFriendList)
return;
WeGameFriendListInfo friendListInfo;
message.Parse<WeGameFriendListInfo>(out friendListInfo);
this.UpdateFriendList(friendListInfo);
}
private void UpdateFriendList(WeGameFriendListInfo friendListInfo)
{
this._wegameFriendList = friendListInfo._friendList;
WeGameHelper.WriteDebugString("On update friend list - " + this.DumpFriendListString(friendListInfo._friendList));
}
private bool IsWeGameFriend(RailID id)
{
bool flag = false;
if (this._wegameFriendList != null)
{
foreach (RailFriendInfo wegameFriend in this._wegameFriendList)
{
if (RailComparableID.op_Equality((RailComparableID) wegameFriend.friend_rail_id, (RailComparableID) id))
{
flag = true;
break;
}
}
}
return flag;
}
private string DumpFriendListString(List<RailFriendInfo> list)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (RailFriendInfo railFriendInfo in list)
stringBuilder.AppendLine(string.Format("friend_id: {0}, type: {1}, online: {2}, playing: {3}", (object) (ulong) ((RailComparableID) railFriendInfo.friend_rail_id).id_, (object) (EnumRailFriendType) railFriendInfo.friend_type, (object) ((RailFriendOnLineState) railFriendInfo.online_state).friend_online_state.ToString(), (object) (uint) ((RailFriendOnLineState) railFriendInfo.online_state).game_define_game_playing_state));
return stringBuilder.ToString();
}
private bool IsActiveUser(RailID user) => this._connectionStateMap.ContainsKey(user) && (uint) this._connectionStateMap[user] > 0U;
private void UpdateUserStateBySessionAuthResult(GameServerStartSessionWithPlayerResponse data)
{
RailID remoteRailId = (RailID) data.remote_rail_id;
RailResult result = (RailResult) ((EventBase) data).result;
if (!this._connectionStateMap.ContainsKey(remoteRailId))
return;
if (result == null)
{
WeGameHelper.WriteDebugString("UpdateUserStateBySessionAuthResult Auth Success");
this.BroadcastConnectedUsers();
}
else
{
WeGameHelper.WriteDebugString("UpdateUserStateBySessionAuthResult Auth Failed");
this.CloseAndUpdateUserState(remoteRailId);
}
}
private bool TryAuthUserByRecvData(RailID user, byte[] data, int length)
{
WeGameHelper.WriteDebugString("TryAuthUserByRecvData user:{0}", (object) (ulong) ((RailComparableID) user).id_);
if (length < 3)
{
WeGameHelper.WriteDebugString("Failed to validate authentication packet: Too short. (Length: " + (object) length + ")");
return false;
}
int num = (int) data[1] << 8 | (int) data[0];
if (num != length)
{
WeGameHelper.WriteDebugString("Failed to validate authentication packet: Packet size mismatch. (" + (object) num + "!=" + (object) length + ")");
return false;
}
if (data[2] == (byte) 93)
return true;
WeGameHelper.WriteDebugString("Failed to validate authentication packet: Packet type is not correct. (Type: " + (object) data[2] + ")");
return false;
}
private bool OnPacketRead(byte[] data, int size, RailID user)
{
if (!this.IsActiveUser(user))
{
WeGameHelper.WriteDebugString("OnPacketRead IsActiveUser false");
return false;
}
NetSocialModule.ConnectionState connectionState = this._connectionStateMap[user];
if (connectionState != NetSocialModule.ConnectionState.Authenticating)
return connectionState == NetSocialModule.ConnectionState.Connected;
if (!this.TryAuthUserByRecvData(user, data, size))
this.CloseAndUpdateUserState(user);
else
this.OnAuthSuccess(user);
return false;
}
private void OnAuthSuccess(RailID remote_peer)
{
if (!this._connectionStateMap.ContainsKey(remote_peer))
return;
this._connectionStateMap[remote_peer] = NetSocialModule.ConnectionState.Connected;
int length = 3;
byte[] numArray = new byte[length];
numArray[0] = (byte) (length & (int) byte.MaxValue);
numArray[1] = (byte) (length >> 8 & (int) byte.MaxValue);
numArray[2] = (byte) 93;
rail_api.RailFactory().RailNetworkHelper().SendReliableData(this._serverID, remote_peer, numArray, (uint) length);
}
public void OnRailEvent(RAILEventID event_id, EventBase data)
{
WeGameHelper.WriteDebugString("OnRailEvent,id=" + event_id.ToString() + " ,result=" + data.result.ToString());
if (event_id != 3006)
{
if (event_id != 16001)
{
if (event_id != 16002)
return;
this.OnCreateSessionFailed((CreateSessionFailed) data);
}
else
this.OnCreateSessionRequest((CreateSessionRequest) data);
}
else
this.UpdateUserStateBySessionAuthResult((GameServerStartSessionWithPlayerResponse) data);
}
private void OnLobbyCreated(RailID lobbyID)
{
WeGameHelper.WriteDebugString("SetLocalPeer: {0}", (object) (ulong) ((RailComparableID) lobbyID).id_);
this._reader.SetLocalPeer(lobbyID);
this._writer.SetLocalPeer(lobbyID);
this._serverID = lobbyID;
Action action = (Action) (() =>
{
// ISSUE: explicit non-virtual call
ReportServerID t = new ReportServerID()
{
_serverID = __nonvirtual (((RailComparableID) lobbyID).id_.ToString())
};
IPCMessage msg = new IPCMessage();
msg.Build<ReportServerID>(IPCMessageType.IPCMessageTypeReportServerID, t);
WeGameHelper.WriteDebugString("Send serverID to game client - " + this._client.SendMessage(msg).ToString());
});
if (this._serverConnected)
{
action();
}
else
{
this._ipcConnetedAction += action;
WeGameHelper.WriteDebugString("report server id fail, no connection");
}
}
private void RegisterRailEvent()
{
RAILEventID[] railEventIdArray = new RAILEventID[4]
{
(RAILEventID) 16001,
(RAILEventID) 16002,
(RAILEventID) 3006,
(RAILEventID) 3005
};
foreach (int num in railEventIdArray)
{
// ISSUE: method pointer
this._callbackHelper.RegisterCallback((RAILEventID) num, new RailEventCallBackHandler((object) this, __methodptr(OnRailEvent)));
}
}
public override void Initialize()
{
base.Initialize();
this._mode |= ServerMode.Lobby;
this.RegisterRailEvent();
this._reader.SetReadEvent(new WeGameP2PReader.OnReadEvent(this.OnPacketRead));
if (Program.LaunchParameters.ContainsKey("-lobby"))
{
this._mode |= ServerMode.Lobby;
string launchParameter = Program.LaunchParameters["-lobby"];
if (!(launchParameter == "private"))
{
if (launchParameter == "friends")
{
this._mode |= ServerMode.FriendsCanJoin;
this._lobby.Create(false);
}
else
Console.WriteLine(Language.GetTextValue("Error.InvalidLobbyFlag", (object) "private", (object) "friends"));
}
else
this._lobby.Create(true);
}
if (Program.LaunchParameters.ContainsKey("-friendsoffriends"))
this._mode |= ServerMode.FriendsOfFriends;
this._client.Init("WeGame.Terraria.Message.Client", "WeGame.Terraria.Message.Server");
this._client.OnConnected += new Action(this.OnConnected);
this._client.OnMessage += new Action<IPCMessage>(this.OnWegameMessage);
CoreSocialModule.OnTick += new Action(this._client.Tick);
this._client.Start();
}
public override ulong GetLobbyId() => (ulong) ((RailComparableID) this._serverID).id_;
public override void OpenInviteInterface()
{
}
public override void CancelJoin()
{
}
public override bool CanInvite() => false;
public override void LaunchLocalServer(Process process, ServerMode mode)
{
}
public override bool StartListening(SocketConnectionAccepted callback)
{
this._acceptingClients = true;
this._connectionAcceptedCallback = callback;
return false;
}
public override void StopListening() => this._acceptingClients = false;
public override void Connect(RemoteAddress address)
{
}
public override void Close(RemoteAddress address) => this.CloseAndUpdateUserState(this.RemoteAddressToRailId(address));
}
}

View file

@ -0,0 +1,86 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.NetSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System;
using System.Collections.Concurrent;
using Terraria.Net;
namespace Terraria.Social.WeGame
{
public abstract class NetSocialModule : Terraria.Social.Base.NetSocialModule
{
protected const int LobbyMessageJoin = 1;
protected Lobby _lobby = new Lobby();
protected WeGameP2PReader _reader;
protected WeGameP2PWriter _writer;
protected ConcurrentDictionary<RailID, NetSocialModule.ConnectionState> _connectionStateMap = new ConcurrentDictionary<RailID, NetSocialModule.ConnectionState>();
protected static readonly byte[] _handshake = new byte[10]
{
(byte) 10,
(byte) 0,
(byte) 93,
(byte) 114,
(byte) 101,
(byte) 108,
(byte) 111,
(byte) 103,
(byte) 105,
(byte) 99
};
protected NetSocialModule()
{
this._reader = new WeGameP2PReader();
this._writer = new WeGameP2PWriter();
}
public override void Initialize()
{
CoreSocialModule.OnTick += new Action(this._reader.ReadTick);
CoreSocialModule.OnTick += new Action(this._writer.SendAll);
}
public override void Shutdown() => this._lobby.Leave();
public override bool IsConnected(RemoteAddress address)
{
if (address == null)
return false;
RailID railId = this.RemoteAddressToRailId(address);
return this._connectionStateMap.ContainsKey(railId) && this._connectionStateMap[railId] == NetSocialModule.ConnectionState.Connected;
}
protected RailID GetLocalPeer() => rail_api.RailFactory().RailPlayer().GetRailID();
protected bool GetSessionState(RailID userId, RailNetworkSessionState state)
{
if (rail_api.RailFactory().RailNetworkHelper().GetSessionState(userId, state) == null)
return true;
WeGameHelper.WriteDebugString("GetSessionState Failed user:{0}", (object) (ulong) ((RailComparableID) userId).id_);
return false;
}
protected RailID RemoteAddressToRailId(RemoteAddress address) => ((WeGameAddress) address).rail_id;
public override bool Send(RemoteAddress address, byte[] data, int length)
{
this._writer.QueueSend(this.RemoteAddressToRailId(address), data, length);
return true;
}
public override int Receive(RemoteAddress address, byte[] data, int offset, int length) => address == null ? 0 : this._reader.Receive(this.RemoteAddressToRailId(address), data, offset, length);
public override bool IsDataAvailable(RemoteAddress address) => this._reader.IsDataAvailable(this.RemoteAddressToRailId(address));
public enum ConnectionState
{
Inactive,
Authenticating,
Connected,
}
}
}

View file

@ -0,0 +1,35 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.OverlaySocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
namespace Terraria.Social.WeGame
{
public class OverlaySocialModule : Terraria.Social.Base.OverlaySocialModule
{
private bool _gamepadTextInputActive;
public override void Initialize()
{
}
public override void Shutdown()
{
}
public override bool IsGamepadTextInputActive() => this._gamepadTextInputActive;
public override bool ShowGamepadTextInput(
string description,
uint maxLength,
bool multiLine = false,
string existingText = "",
bool password = false)
{
return false;
}
public override string GetGamepadText() => "";
}
}

View file

@ -0,0 +1,17 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.ReportServerID
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System.Runtime.Serialization;
namespace Terraria.Social.WeGame
{
[DataContract]
public class ReportServerID
{
[DataMember]
public string _serverID;
}
}

View file

@ -0,0 +1,19 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.WeGameFriendListInfo
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Terraria.Social.WeGame
{
[DataContract]
public class WeGameFriendListInfo
{
[DataMember]
public List<RailFriendInfo> _friendList;
}
}

View file

@ -0,0 +1,44 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.WeGameHelper
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Json;
using System.Text;
namespace Terraria.Social.WeGame
{
public class WeGameHelper
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern void OutputDebugString(string message);
public static void WriteDebugString(string format, params object[] args)
{
string str = "[WeGame] - " + format;
}
public static string Serialize<T>(T data)
{
using (MemoryStream memoryStream = new MemoryStream())
{
new DataContractJsonSerializer(typeof (T)).WriteObject((Stream) memoryStream, (object) data);
memoryStream.Position = 0L;
using (StreamReader streamReader = new StreamReader((Stream) memoryStream, Encoding.UTF8))
return streamReader.ReadToEnd();
}
}
public static void UnSerialize<T>(string str, out T data)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(str)))
{
DataContractJsonSerializer contractJsonSerializer = new DataContractJsonSerializer(typeof (T));
data = (T) contractJsonSerializer.ReadObject((Stream) memoryStream);
}
}
}
}

View file

@ -0,0 +1,138 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.WeGameP2PReader
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System;
using System.Collections.Generic;
namespace Terraria.Social.WeGame
{
public class WeGameP2PReader
{
public object RailLock = new object();
private const int BUFFER_SIZE = 4096;
private Dictionary<RailID, Queue<WeGameP2PReader.ReadResult>> _pendingReadBuffers = new Dictionary<RailID, Queue<WeGameP2PReader.ReadResult>>();
private Queue<RailID> _deletionQueue = new Queue<RailID>();
private Queue<byte[]> _bufferPool = new Queue<byte[]>();
private WeGameP2PReader.OnReadEvent _readEvent;
private RailID _local_id;
public void ClearUser(RailID id)
{
lock (this._pendingReadBuffers)
this._deletionQueue.Enqueue(id);
}
public bool IsDataAvailable(RailID id)
{
lock (this._pendingReadBuffers)
{
if (!this._pendingReadBuffers.ContainsKey(id))
return false;
Queue<WeGameP2PReader.ReadResult> pendingReadBuffer = this._pendingReadBuffers[id];
return pendingReadBuffer.Count != 0 && pendingReadBuffer.Peek().Size != 0U;
}
}
public void SetReadEvent(WeGameP2PReader.OnReadEvent method) => this._readEvent = method;
private bool IsPacketAvailable(out uint size)
{
lock (this.RailLock)
{
IRailNetwork irailNetwork = rail_api.RailFactory().RailNetworkHelper();
RailID railId1 = new RailID();
((RailComparableID) railId1).id_ = ((RailComparableID) this.GetLocalPeer()).id_;
RailID railId2 = railId1;
ref uint local = ref size;
return irailNetwork.IsDataReady(railId2, ref local);
}
}
private RailID GetLocalPeer() => this._local_id;
public void SetLocalPeer(RailID rail_id)
{
if (RailComparableID.op_Equality((RailComparableID) this._local_id, (RailComparableID) null))
this._local_id = new RailID();
((RailComparableID) this._local_id).id_ = ((RailComparableID) rail_id).id_;
}
private bool IsValid() => RailComparableID.op_Inequality((RailComparableID) this._local_id, (RailComparableID) null) && ((RailComparableID) this._local_id).IsValid();
public void ReadTick()
{
if (!this.IsValid())
return;
lock (this._pendingReadBuffers)
{
while (this._deletionQueue.Count > 0)
this._pendingReadBuffers.Remove(this._deletionQueue.Dequeue());
uint size;
while (this.IsPacketAvailable(out size))
{
byte[] data = this._bufferPool.Count != 0 ? this._bufferPool.Dequeue() : new byte[(int) Math.Max(size, 4096U)];
RailID railId = new RailID();
bool flag;
lock (this.RailLock)
flag = rail_api.RailFactory().RailNetworkHelper().ReadData(this.GetLocalPeer(), railId, data, size) == 0;
if (flag)
{
if (this._readEvent == null || this._readEvent(data, (int) size, railId))
{
if (!this._pendingReadBuffers.ContainsKey(railId))
this._pendingReadBuffers[railId] = new Queue<WeGameP2PReader.ReadResult>();
this._pendingReadBuffers[railId].Enqueue(new WeGameP2PReader.ReadResult(data, size));
}
else
this._bufferPool.Enqueue(data);
}
}
}
}
public int Receive(RailID user, byte[] buffer, int bufferOffset, int bufferSize)
{
uint num1 = 0;
lock (this._pendingReadBuffers)
{
if (!this._pendingReadBuffers.ContainsKey(user))
return 0;
Queue<WeGameP2PReader.ReadResult> pendingReadBuffer = this._pendingReadBuffers[user];
while (pendingReadBuffer.Count > 0)
{
WeGameP2PReader.ReadResult readResult = pendingReadBuffer.Peek();
uint num2 = Math.Min((uint) bufferSize - num1, readResult.Size - readResult.Offset);
if (num2 == 0U)
return (int) num1;
Array.Copy((Array) readResult.Data, (long) readResult.Offset, (Array) buffer, (long) bufferOffset + (long) num1, (long) num2);
if ((int) num2 == (int) readResult.Size - (int) readResult.Offset)
this._bufferPool.Enqueue(pendingReadBuffer.Dequeue().Data);
else
readResult.Offset += num2;
num1 += num2;
}
}
return (int) num1;
}
public class ReadResult
{
public byte[] Data;
public uint Size;
public uint Offset;
public ReadResult(byte[] data, uint size)
{
this.Data = data;
this.Size = size;
this.Offset = 0U;
}
}
public delegate bool OnReadEvent(byte[] data, int size, RailID user);
}
}

View file

@ -0,0 +1,117 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.WeGame.WeGameP2PWriter
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using rail;
using System;
using System.Collections.Generic;
namespace Terraria.Social.WeGame
{
public class WeGameP2PWriter
{
private const int BUFFER_SIZE = 1024;
private RailID _local_id;
private Dictionary<RailID, Queue<WeGameP2PWriter.WriteInformation>> _pendingSendData = new Dictionary<RailID, Queue<WeGameP2PWriter.WriteInformation>>();
private Dictionary<RailID, Queue<WeGameP2PWriter.WriteInformation>> _pendingSendDataSwap = new Dictionary<RailID, Queue<WeGameP2PWriter.WriteInformation>>();
private Queue<byte[]> _bufferPool = new Queue<byte[]>();
private object _lock = new object();
public void QueueSend(RailID user, byte[] data, int length)
{
lock (this._lock)
{
Queue<WeGameP2PWriter.WriteInformation> writeInformationQueue;
if (this._pendingSendData.ContainsKey(user))
writeInformationQueue = this._pendingSendData[user];
else
this._pendingSendData[user] = writeInformationQueue = new Queue<WeGameP2PWriter.WriteInformation>();
int val1 = length;
int sourceIndex = 0;
while (val1 > 0)
{
WeGameP2PWriter.WriteInformation writeInformation;
if (writeInformationQueue.Count == 0 || 1024 - writeInformationQueue.Peek().Size == 0)
{
writeInformation = this._bufferPool.Count <= 0 ? new WeGameP2PWriter.WriteInformation() : new WeGameP2PWriter.WriteInformation(this._bufferPool.Dequeue());
writeInformationQueue.Enqueue(writeInformation);
}
else
writeInformation = writeInformationQueue.Peek();
int length1 = Math.Min(val1, 1024 - writeInformation.Size);
Array.Copy((Array) data, sourceIndex, (Array) writeInformation.Data, writeInformation.Size, length1);
writeInformation.Size += length1;
val1 -= length1;
sourceIndex += length1;
}
}
}
public void ClearUser(RailID user)
{
lock (this._lock)
{
if (this._pendingSendData.ContainsKey(user))
{
Queue<WeGameP2PWriter.WriteInformation> writeInformationQueue = this._pendingSendData[user];
while (writeInformationQueue.Count > 0)
this._bufferPool.Enqueue(writeInformationQueue.Dequeue().Data);
}
if (!this._pendingSendDataSwap.ContainsKey(user))
return;
Queue<WeGameP2PWriter.WriteInformation> writeInformationQueue1 = this._pendingSendDataSwap[user];
while (writeInformationQueue1.Count > 0)
this._bufferPool.Enqueue(writeInformationQueue1.Dequeue().Data);
}
}
public void SetLocalPeer(RailID rail_id)
{
if (RailComparableID.op_Equality((RailComparableID) this._local_id, (RailComparableID) null))
this._local_id = new RailID();
((RailComparableID) this._local_id).id_ = ((RailComparableID) rail_id).id_;
}
private RailID GetLocalPeer() => this._local_id;
private bool IsValid() => RailComparableID.op_Inequality((RailComparableID) this._local_id, (RailComparableID) null) && ((RailComparableID) this._local_id).IsValid();
public void SendAll()
{
if (!this.IsValid())
return;
lock (this._lock)
Utils.Swap<Dictionary<RailID, Queue<WeGameP2PWriter.WriteInformation>>>(ref this._pendingSendData, ref this._pendingSendDataSwap);
foreach (KeyValuePair<RailID, Queue<WeGameP2PWriter.WriteInformation>> keyValuePair in this._pendingSendDataSwap)
{
Queue<WeGameP2PWriter.WriteInformation> writeInformationQueue = keyValuePair.Value;
while (writeInformationQueue.Count > 0)
{
WeGameP2PWriter.WriteInformation writeInformation = writeInformationQueue.Dequeue();
int num = rail_api.RailFactory().RailNetworkHelper().SendData(this.GetLocalPeer(), keyValuePair.Key, writeInformation.Data, (uint) writeInformation.Size) == 0 ? 1 : 0;
this._bufferPool.Enqueue(writeInformation.Data);
}
}
}
public class WriteInformation
{
public byte[] Data;
public int Size;
public WriteInformation()
{
this.Data = new byte[1024];
this.Size = 0;
}
public WriteInformation(byte[] data)
{
this.Data = data;
this.Size = 0;
}
}
}
}