diff --git a/AssemblyInfoCommon.cs b/AssemblyInfoCommon.cs new file mode 100644 index 0000000..f1919a8 --- /dev/null +++ b/AssemblyInfoCommon.cs @@ -0,0 +1,21 @@ +using System.Reflection; + +//Common AssemblyInfo +// Les informations générales relatives à un assembly dépendent de +// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations +// associées à un assembly. +[assembly: AssemblyCompany("sheychen")] +[assembly: AssemblyCopyright("Copyright © 2016")] + +// Les informations de version pour un assembly se composent des quatre valeurs suivantes : +// +// Version principale +// Version secondaire +// Numéro de build +// Révision +// +// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut +// en utilisant '*', comme indiqué ci-dessous : +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.1.0.1")] +[assembly: AssemblyFileVersion("1.1.0.1")] \ No newline at end of file diff --git a/Galactic Colors Control Common/Binary.cs b/Galactic Colors Control Common/Binary.cs new file mode 100644 index 0000000..9d9b905 --- /dev/null +++ b/Galactic Colors Control Common/Binary.cs @@ -0,0 +1,131 @@ +using System; +using System.Linq; +using System.Text; + +namespace Galactic_Colors_Control_Common +{ + /// + /// All used types - byte[] convertions + /// + public static class Binary + { + public static bool ToBool(ref byte[] bytes) + { + byte[] data = new byte[1]; + data = bytes.Take(1).ToArray(); + RemoveFirst(ref bytes, 1); + return data[1] == 1 ? true : false; + } + + ///1 byte + public static byte[] FromBool(bool x) + { + return x ? new byte[1] { 1 } : new byte[1] { 0 }; + } + + public static string ToString(ref byte[] bytes) + { + int len = ToInt(ref bytes); + string text = Encoding.ASCII.GetString(bytes.Take(len).ToArray()); + RemoveFirst(ref bytes, len); + return text; + } + + ///len(in bytes) + string + public static byte[] FromString(string text) + { + byte[] data = Encoding.ASCII.GetBytes(text); + return AddBytes(FromInt(data.Length), data); + } + + public static int ToInt(ref byte[] bytes) + { + if (bytes == null) + return -1; + + if (bytes.Length < 4) + return -1; + + byte[] data = new byte[4]; + data = bytes.Take(4).ToArray(); + data.Reverse(); + RemoveFirst(ref bytes, 4); + return BitConverter.ToInt32(data, 0); + } + + ///4 bytes + public static byte[] FromInt(int x) + { + byte[] data = new byte[4]; + data = BitConverter.GetBytes(x); + return data; + } + + public static string[] ToStringArray(ref byte[] bytes) + { + int len = ToInt(ref bytes); + if (len < 1 || len > 10000) + return new string[0]; + + string[] data = new string[len]; + for (int i = 0; i < len; i++) + { + data[i] = ToString(ref bytes); + } + return data; + } + + public static byte[] FromStringArray(string[] array) + { + if (array == null) + return new byte[0]; + + byte[] data = FromInt(array.Length); + for (int i = 0; i < array.Length; i++) + { + data = AddBytes(data, FromString(array[i])); + } + return data; + } + + public static int[] ToIntArray(ref byte[] bytes) + { + int len = ToInt(ref bytes); + int[] data = new int[len]; + for (int i = 0; i < len; i++) + { + data[i] = ToInt(ref bytes); + } + return data; + } + + public static byte[] FromIntArray(int[] array) + { + byte[] data = FromInt(array.Length); + for (int i = 0; i < array.Length; i++) + { + data = AddBytes(data, FromInt(array[i])); + } + return data; + } + + public static byte[] AddBytes(params byte[][] arguments) + { + byte[] res = new byte[arguments.Sum(a => a.Length)]; + int offset = 0; + for (int i = 0; i < arguments.Length; i++) + { + Buffer.BlockCopy(arguments[i], 0, res, offset, arguments[i].Length); + offset += arguments[i].Length; + } + return res; + } + + public static void RemoveFirst(ref byte[] bytes, int count) + { + byte[] newbytes = new byte[bytes.Length - count]; + newbytes = bytes.Skip(count).ToArray(); + bytes = newbytes; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Common.cs b/Galactic Colors Control Common/Common.cs new file mode 100644 index 0000000..8bf281f --- /dev/null +++ b/Galactic Colors Control Common/Common.cs @@ -0,0 +1,74 @@ +using System; +using System.Linq; + +namespace Galactic_Colors_Control_Common +{ + public static class Common + { + /// + /// Write line in console with correct colors + /// + /// Text to write + /// Foreground color + /// Background color + public static void ConsoleWrite(string v, ConsoleColor Fore = ConsoleColor.White, ConsoleColor Back = ConsoleColor.Black) + { + Console.Write("\b"); + Console.ForegroundColor = Fore; + Console.BackgroundColor = Back; + Console.WriteLine(v); + ConsoleResetColor(); + Console.Write(">"); + } + + /// + /// Reset Console Colors + /// For non black background console as Ubuntu + /// + public static void ConsoleResetColor() + { + Console.ResetColor(); + Console.BackgroundColor = ConsoleColor.Black; + } + + /// + /// Simpler string array creation + /// + public static string[] Strings(params string[] args) + { + return args; + } + + public static string ArrayToString(string[] array) + { + string text = ""; + if (array != null) + { + foreach (string str in array) + { + text += ((text == "" ? "" : Environment.NewLine) + str); + } + } + return text; + } + + public static string ArrayToString(int[] array) + { + string text = ""; + foreach (int i in array) + { + text += ((text == "" ? "" : Environment.NewLine) + i.ToString()); + } + return text; + } + + public static string[] SplitArgs(string text) + { + return text.Split('"') + .Select((element, index) => index % 2 == 0 + ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) + : new string[] { element }) + .SelectMany(element => element).ToArray(); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Galactic Colors Control Common.csproj b/Galactic Colors Control Common/Galactic Colors Control Common.csproj new file mode 100644 index 0000000..10505e4 --- /dev/null +++ b/Galactic Colors Control Common/Galactic Colors Control Common.csproj @@ -0,0 +1,84 @@ + + + + + Debug + AnyCPU + {022A69CE-22B5-4934-BE9F-A9C6DF9557ED} + Library + Properties + Galactic_Colors_Control_Common + Galactic Colors Control Common + v4.5 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Properties\AssemblyInfoCommon.cs + + + + + + + + True + True + Resources.resx + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + + + \ No newline at end of file diff --git a/Galactic Colors Control Common/Logger.cs b/Galactic Colors Control Common/Logger.cs new file mode 100644 index 0000000..a78c31a --- /dev/null +++ b/Galactic Colors Control Common/Logger.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Galactic_Colors_Control_Common +{ + public class Logger + { + public enum logType { dev, debug, info, warm, error, fatal } + public enum logConsole { normal, show, hide } + + public struct Log + { + public string text; + public logType type; + public logConsole console; + + public Log(string p1, logType p2, logConsole p3 = logConsole.normal) + { + text = p1; + type = p2; + console = p3; + } + } + + private List toWriteLogs = new List(); + private string logPath; + private ConsoleColor[] logBackColor; + private ConsoleColor[] logForeColor; + private Thread Updater; + private logType logLevel = logType.info; + private bool _run = true; + public bool run { get { return _run; } } + private static bool _debug = false; + private static bool _dev = false; + + /// + /// Create log file and start logger thread + /// + /// Absolute path to logs directory + public void Initialise(string LogPath, ConsoleColor[] backColor, ConsoleColor[] foreColor, logType LogLevel, bool debug, bool dev) + { + logPath = LogPath; + logBackColor = backColor; + logForeColor = foreColor; + logLevel = LogLevel; + _debug = debug; + _dev = dev; + if (!Directory.Exists(logPath)) + { + Directory.CreateDirectory(logPath); + Write("Log Directory Created", logType.info); + } + else + { + //Sort old logs + string[] files = Directory.GetFiles(logPath); + foreach (string file in files) + { + if (Path.GetExtension(file) == ".log") + { + string name = Path.GetFileName(file); + name = name.Substring(0, Math.Min(name.Length, 10)); + if (name.Length == 10) + { + if (name != DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)) + { + int y; + int m; + int d; + if (int.TryParse(new string(name.Take(4).ToArray()), out y) && int.TryParse(new string(name.Skip(5).Take(2).ToArray()), out m) && int.TryParse(new string(name.Skip(8).Take(2).ToArray()), out d)) + { + if (!Directory.Exists(logPath + "/" + y + "/" + m + "/" + d)) + { + Directory.CreateDirectory(logPath + "/" + y + "/" + m + "/" + d); + } + File.Move(file, logPath + "/" + y + "/" + m + "/" + d + "/" + Path.GetFileName(file)); + } + } + } + } + } + } + int i = 0; + while (File.Exists(logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; } + logPath = logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log"; + Write("Log path:" + logPath, logType.debug); + Updater = new Thread(new ThreadStart(UpdaterLoop)); + Updater.Start(); + } + + public void Join() + { + _run = false; + Updater.Join(); + } + + public void ChangeLevel(logType level) + { + logLevel = level; + Write("Change to " + logLevel.ToString(), logType.info, logConsole.show); + } + + /// + /// Add log to log pile + /// + /// Log text + /// Log status + /// Server display modifier + public void Write(string text, logType type, logConsole console = logConsole.normal) + { + Write(new Log(text, type, console)); + } + + /// + /// Add log to log pile + /// + /// Log struct + private void Write(Log log) + { + if (_debug || _dev) + { + //Add Source Method + log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text; + } + toWriteLogs.Add(log); + } + + /// + /// Write log pile to logfile and console + /// + public void UpdaterLoop() + { + while (_run || toWriteLogs.Count > 0) + { + while (toWriteLogs.Count > 0) + { + Log log = toWriteLogs[0]; + if (log.type >= logLevel) + { + File.AppendAllText(logPath, DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine); + if (log.console != logConsole.hide) + { + ConsoleWrite(log); + } + } + else + { + if (log.console == logConsole.show) + { + ConsoleWrite(log); + } + } + toWriteLogs.Remove(log); + } + Thread.Sleep(200); + } + } + + private void ConsoleWrite(Log log) + { + Console.BackgroundColor = logBackColor[(int)log.type]; + Console.ForegroundColor = logForeColor[(int)log.type]; + Console.Write("\b"); + Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text); + Common.ConsoleResetColor(); + Console.Write(">"); + } + } +} diff --git a/Galactic Colors Control Common/MultiLang.cs b/Galactic Colors Control Common/MultiLang.cs new file mode 100644 index 0000000..f2bcd4a --- /dev/null +++ b/Galactic Colors Control Common/MultiLang.cs @@ -0,0 +1,82 @@ +using Galactic_Colors_Control_Common.Protocol; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Galactic_Colors_Control_Common +{ + public class MultiLang + { + private Dictionary> _multiDictionary = new Dictionary>(); //List of phrases by key + private List _Langs = new List(); //Readable langs list + + public Dictionary> multiDictionary { get { return _multiDictionary; } } + public List Langs { get { return _Langs; } } + + public void Load() + { + _multiDictionary.Clear(); + _Langs.Clear(); + string[] lines = Properties.Resources.Lang.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries); //Load from .cvs ressources. //TODO add more langs + _Langs = lines[0].Split(';').OfType().ToList(); + _Langs.RemoveAt(0); + foreach (string line in lines) + { + List items = line.Split(';').OfType().ToList(); + string key = items[0]; + items.RemoveAt(0); + _multiDictionary.Add(key, items); + } + } + + public string GetEventText(EventData eve, int lang) + { + string data = Common.ArrayToString(eve.data); + switch (eve.type) + { + case EventTypes.ChatMessage: + return data; + + case EventTypes.PartyJoin: + case EventTypes.PartyLeave: + case EventTypes.ServerJoin: + case EventTypes.ServerLeave: + return data + " " + Get(eve.type.ToString(), lang); + + default: + return eve.ToSmallString(); + } + } + + public string GetResultText(ResultData res, int lang) + { + string data = Common.ArrayToString(res.result); + if (res.type == ResultTypes.Error) + data = Get("Error", lang) + ": " + data; + return data; + } + + public string Get(string Key, int Lang) + { + string text = ""; + + if (_multiDictionary.ContainsKey(Key)) + { + if (_multiDictionary[Key].Count >= Lang) + { + text = _multiDictionary[Key][Lang]; + } + else + { + text = "!!!UNKNOW LANG KEY!!!"; + } + } + else + { + text = "!!!UNKNOW WORD KEY!!!"; + } + + return text; + } + } +} diff --git a/Galactic Colors Control Common/Properties/AssemblyInfo.cs b/Galactic Colors Control Common/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f8b2f83 --- /dev/null +++ b/Galactic Colors Control Common/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// Les informations générales relatives à un assembly dépendent de +// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations +// associées à un assembly. +[assembly: AssemblyTitle("Galactic Colors Control Common")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyProduct("Galactic Colors Control Common")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly +// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de +// COM, affectez la valeur true à l'attribut ComVisible sur ce type. +[assembly: ComVisible(false)] + +// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM +[assembly: Guid("022a69ce-22b5-4934-be9f-a9c6df9557ed")] \ No newline at end of file diff --git a/Galactic Colors Control Common/Properties/Resources.Designer.cs b/Galactic Colors Control Common/Properties/Resources.Designer.cs new file mode 100644 index 0000000..cf78310 --- /dev/null +++ b/Galactic Colors Control Common/Properties/Resources.Designer.cs @@ -0,0 +1,87 @@ +//------------------------------------------------------------------------------ +// +// Ce code a été généré par un outil. +// Version du runtime :4.0.30319.42000 +// +// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si +// le code est régénéré. +// +//------------------------------------------------------------------------------ + +namespace Galactic_Colors_Control_Common.Properties { + using System; + + + /// + /// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées. + /// + // Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder + // à l'aide d'un outil, tel que ResGen ou Visual Studio. + // Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen + // avec l'option /str ou régénérez votre projet VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Retourne l'instance ResourceManager mise en cache utilisée par cette classe. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Galactic_Colors_Control_Common.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Remplace la propriété CurrentUICulture du thread actuel pour toutes + /// les recherches de ressources à l'aide de cette classe de ressource fortement typée. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Recherche une chaîne localisée semblable à Key;Français;English + ///Registered;Enregistré;Registered + ///Not Registered;Non Enregistré;Not Registered + ///File;Fichier;File + ///Export;Exporter;Export + ///Quit;Quitter;Quit + ///Licence;Licence;License + ///Language;Langue;Language + ///Help;Aide;Help + ///About;À Propos;About + ///QuitConfirm;Êtes-vous certain de vouloir quitter CycleMollier ?;Are you sure than you would like to quit CycleMollier ? + ///BP;Basse Pression;Low Pressure + ///HP;Haute Pression;High Pressure + ///InBar;(En Bar);(In Bar) + ///Draw;Tracer;Draw + ///DrawText;Tracer le diagramme e [le reste de la chaîne a été tronqué]";. + /// + internal static string Lang { + get { + return ResourceManager.GetString("Lang", resourceCulture); + } + } + } +} diff --git a/Galactic Colors Control Common/Properties/Resources.resx b/Galactic Colors Control Common/Properties/Resources.resx new file mode 100644 index 0000000..341ce7a --- /dev/null +++ b/Galactic Colors Control Common/Properties/Resources.resx @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\Resources\Lang.csv;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + \ No newline at end of file diff --git a/Galactic Colors Control Common/Protocol/Data.cs b/Galactic Colors Control Common/Protocol/Data.cs new file mode 100644 index 0000000..951f671 --- /dev/null +++ b/Galactic Colors Control Common/Protocol/Data.cs @@ -0,0 +1,56 @@ +namespace Galactic_Colors_Control_Common.Protocol +{ + /// + /// Packet Master Class + /// + public class Data + { + public enum DataType { Request, Result, Event }; + + /// + /// Create Packet from bytes + /// + /// row bytes (remove used bytes) + public static Data FromBytes(ref byte[] bytes) + { + switch ((DataType)Binary.ToInt(ref bytes)) + { + case DataType.Request: + return new RequestData(ref bytes); + + case DataType.Result: + return new ResultData(ref bytes); + + case DataType.Event: + return new EventData(ref bytes); + + default: + return null; + } + } + + /// + /// Small readable text + /// + public virtual string ToSmallString() + { + return null; + } + + /// + /// Long readble text + /// + public virtual string ToLongString() + { + return null; + } + + /// + /// Generate bytes to send + /// + public virtual byte[] ToBytes() + { + return new byte[0]; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Protocol/EventData.cs b/Galactic Colors Control Common/Protocol/EventData.cs new file mode 100644 index 0000000..7918063 --- /dev/null +++ b/Galactic Colors Control Common/Protocol/EventData.cs @@ -0,0 +1,49 @@ +namespace Galactic_Colors_Control_Common.Protocol +{ + public enum EventTypes + { + ChatMessage, //To displat in chatbox + ServerJoin, //A player join server + ServerLeave, //A player leave server + ServerKick, //You are kick from server + PartyJoin, //A player join your party + PartyLeave, //A player leave your party + PartyKick //Tou are jick from your party + } + + /// + /// Server to Client Packet + /// + public class EventData : Data + { + public EventTypes type; + public string[] data; //EventArgs like + + public EventData(EventTypes Type, string[] Data = null) + { + type = Type; + data = Data; + } + + public EventData(ref byte[] bytes) + { + type = (EventTypes)Binary.ToInt(ref bytes); + data = Binary.ToStringArray(ref bytes); + } + + public override byte[] ToBytes() + { + return Binary.AddBytes(Binary.FromInt((int)DataType.Event), Binary.FromInt((int)type), Binary.FromStringArray(data)); + } + + public override string ToSmallString() + { + return type.ToString() + "|" + Common.ArrayToString(data); + } + + public override string ToLongString() + { + return "Event : " + ToSmallString(); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Protocol/EventDataArgs.cs b/Galactic Colors Control Common/Protocol/EventDataArgs.cs new file mode 100644 index 0000000..e17413b --- /dev/null +++ b/Galactic Colors Control Common/Protocol/EventDataArgs.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Galactic_Colors_Control_Common.Protocol +{ + /// + /// Hide EventData in EventArgs + /// for OnEvent Handler + /// + public class EventDataArgs : EventArgs + { + private EventData m_Data; + public EventDataArgs(EventData _myData) + { + m_Data = _myData; + } + + public EventData Data { get { return m_Data; } } + } +} diff --git a/Galactic Colors Control Common/Protocol/RequestData.cs b/Galactic Colors Control Common/Protocol/RequestData.cs new file mode 100644 index 0000000..d686c05 --- /dev/null +++ b/Galactic Colors Control Common/Protocol/RequestData.cs @@ -0,0 +1,38 @@ +namespace Galactic_Colors_Control_Common.Protocol +{ + /// + /// Client to Server Data request packet 'allways' return ResultData + /// + public class RequestData : Data + { + public int id; //Client Size autoindent id + public string[] args; + + public RequestData(int Id, string[] Args) + { + id = Id; + args = Args; + } + + public RequestData(ref byte[] bytes) + { + id = Binary.ToInt(ref bytes); + args = Binary.ToStringArray(ref bytes); + } + + public override byte[] ToBytes() + { + return Binary.AddBytes(Binary.FromInt((int)DataType.Request), Binary.FromInt(id), Binary.FromStringArray(args)); + } + + public override string ToSmallString() + { + return Common.ArrayToString(args); + } + + public override string ToLongString() + { + return "Request : " + Common.ArrayToString(args) + "|" + id; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Protocol/RequestResult.cs b/Galactic Colors Control Common/Protocol/RequestResult.cs new file mode 100644 index 0000000..ac90e00 --- /dev/null +++ b/Galactic Colors Control Common/Protocol/RequestResult.cs @@ -0,0 +1,18 @@ +namespace Galactic_Colors_Control_Common.Protocol +{ + /// + /// Part of RequestData + /// Commands return + /// + public class RequestResult + { + public ResultTypes type; + public string[] result; + + public RequestResult(ResultTypes p1, string[] p2 = null) + { + type = p1; + result = p2; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Protocol/ResultData.cs b/Galactic Colors Control Common/Protocol/ResultData.cs new file mode 100644 index 0000000..137891e --- /dev/null +++ b/Galactic Colors Control Common/Protocol/ResultData.cs @@ -0,0 +1,50 @@ +namespace Galactic_Colors_Control_Common.Protocol +{ + public enum ResultTypes { Error, OK } + + /// + /// Server to Client Result from RequestData + /// + public class ResultData : Data + { + public int id; //Client Side Autoindent + public ResultTypes type; + public string[] result; + + public ResultData(int Id, ResultTypes Type, string[] Result = null) + { + id = Id; + type = Type; + result = Result; + } + + public ResultData(int Id, RequestResult Result) + { + id = Id; + type = Result.type; + result = Result.result; + } + + public ResultData(ref byte[] bytes) + { + id = Binary.ToInt(ref bytes); + type = (ResultTypes)Binary.ToInt(ref bytes); + result = Binary.ToStringArray(ref bytes); + } + + public override byte[] ToBytes() + { + return Binary.AddBytes(Binary.FromInt((int)DataType.Result), Binary.FromInt(id), Binary.FromInt((int)type), Binary.FromStringArray(result)); + } + + public override string ToSmallString() + { + return type.ToString() + "|" + Common.ArrayToString(result); + } + + public override string ToLongString() + { + return "Result : " + type.ToString() + "|" + Common.ArrayToString(result) + "|" + id; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Resources/Lang.csv b/Galactic Colors Control Common/Resources/Lang.csv new file mode 100644 index 0000000..487c2e7 --- /dev/null +++ b/Galactic Colors Control Common/Resources/Lang.csv @@ -0,0 +1,52 @@ +Key;Francais;English +GCC;Galactic Colors Control;Galactic Colors Control +Client;Client;Client +Server;Serveur;Server +Console;Console;Console +Loading;Chargement;Loading +OK;OK;OK +Yes;Oui;Yes +No;Non;No +EnterHostname;Saisir l'addresse;Enter hostname +EnterMessage;Saisir un message;Enter message +Connect;Connexion;Connect +Back;Retour;Back +Username;Pseudo;Username +Validate;Valider;Validate +GUI;GUI;GUI +Play;Jouer;Play +Options;Options;Options +Exit;Quitter;Exit +Error;Erreur;Error +Hide;Cacher;Hide +Show;Afficher;Show +Chat;Chat;Chat +Party;Partie;Party +Join;Rejoindre;Join +Use;Utiliser;Use +CantConnect;Connexion impossible. Au revoir;Can't connect sorry. Bye +ServerJoin;rejoint le server;join the server +PartyJoin;rejoint la partie;join the party +ServerLeave;quitte le server;leave the server +PartyLeave;quitte la partie;leave the party +ServerKick;Exclus du serveur;Kick from server +TooShort;Trop court;Too short +TooLong;Trop long;Too long +Update;Actualiser;Update +AnyParty;Aucune partie;Any party +Password;Mot de passe;Password +ClientSide;Cote client;Client side +CantFind:Introuvable;Can't find +Connected:Connecte;Connected +AllreadyTaken;Deja pris;Allready taken +AnyCommand;Aucune commande;Any command +IncorrectArgs;Arguements incorrects;Incorrect Arguements +ExecuteException;Exception d'execution;Execute exception +Access;Acces refuse;Access denied +Allready;Deja fait;Allready do +Format;Format incorrect;Incorrect format +Full;Plein;Full +Close;Fermee;Close +Owner;Proprietaire;Owner +AnyMessage;Aucun message;Any message +MustBeConnected;Doit etre connecte;Must be connected \ No newline at end of file diff --git a/Galactic Colors Control Console/Config.cs b/Galactic Colors Control Console/Config.cs new file mode 100644 index 0000000..e3290f2 --- /dev/null +++ b/Galactic Colors Control Console/Config.cs @@ -0,0 +1,117 @@ +using Galactic_Colors_Control_Common; +using System; +using System.IO; +using System.Xml; +using System.Xml.Serialization; + +namespace Galactic_Colors_Control_Console +{ + [XmlRoot("config")] + public class Config + { + public string logPath = AppDomain.CurrentDomain.BaseDirectory + "Logs"; + public Logger.logType logLevel = Logger.logType.info; + public char commandChar = '/'; + public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White }; + public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; + public int lang = 1; + + /// + /// Load config from xml file + /// App.config is too easy + /// + /// Loaded config + public Config Load() + { + Program.logger.Write("Loading config", Logger.logType.info); + Config config = new Config(); + if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) + { + if (CorrectConfig()) + { + XmlSerializer xs = new XmlSerializer(typeof(Config)); + using (StreamReader re = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) + { + config = xs.Deserialize(re) as Config; + }; + } + else + { + Program.logger.Write("Old config in Config.xml.old", Logger.logType.warm); + File.Delete(AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); + File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); + config.Save(); + } + } + else + { + Program.logger.Write("Any config file", Logger.logType.error); + config.Save(); + } + if (Program._debug) { config.logLevel = Logger.logType.debug; } + if (Program._dev) { config.logLevel = Logger.logType.dev; } + return config; + } + + /// + /// Write actual config in xml file + /// + public void Save() + { + XmlSerializer xs = new XmlSerializer(typeof(Config)); + if (Program._debug || Program._dev) { logLevel = Logger.logType.info; } + using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) + { + xs.Serialize(st, this); + }; + if (Program._debug) { logLevel = Logger.logType.debug; } + if (Program._dev) { logLevel = Logger.logType.dev; } + } + + /// + /// Check config format using Schema + /// + public bool CorrectConfig() + { + bool isCorrect = false; + + using (Stream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", FileMode.Open)) + { + XmlReader re = new XmlTextReader(fs); + XmlSerializer xs = new XmlSerializer(typeof(Config)); + try + { + isCorrect = xs.CanDeserialize(re); + } + catch (XmlException e) + { + isCorrect = false; + Program.logger.Write("Error: " + e.Message, Logger.logType.error); + } + } + + if (isCorrect) + { + try + { + XmlDocument d = new XmlDocument(); + d.Load(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"); + d.Schemas.Add("", XmlReader.Create("ConfigSchema.xsd")); + + d.Validate((o, e) => + { + Program.logger.Write("Error: " + e.Message, Logger.logType.error); + isCorrect = false; + }); + } + catch (XmlException e) + { + isCorrect = false; + Program.logger.Write("Error: " + e.Message, Logger.logType.error); + } + } + + return isCorrect; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Console/ConfigSchema.xsd b/Galactic Colors Control Console/ConfigSchema.xsd new file mode 100644 index 0000000..cf91447 --- /dev/null +++ b/Galactic Colors Control Console/ConfigSchema.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Galactic Colors Control Console/Galactic Colors Control Console.csproj b/Galactic Colors Control Console/Galactic Colors Control Console.csproj index 276d774..30710b6 100644 --- a/Galactic Colors Control Console/Galactic Colors Control Console.csproj +++ b/Galactic Colors Control Console/Galactic Colors Control Console.csproj @@ -44,15 +44,29 @@ + + Properties\AssemblyInfoCommon.cs + + + + {022A69CE-22B5-4934-BE9F-A9C6DF9557ED} + Galactic Colors Control Common + {93582ce8-c8c8-4e19-908b-d671ecbade25} Galactic Colors Control + + + Designer + PreserveNewest + + - - - - - - - + + + + + + + \ No newline at end of file diff --git a/Galactic Colors Control GUI/Program.cs b/Galactic Colors Control GUI/Program.cs index 7360770..18b1aa6 100644 --- a/Galactic Colors Control GUI/Program.cs +++ b/Galactic Colors Control GUI/Program.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using System; namespace Galactic_Colors_Control_GUI { @@ -7,14 +8,33 @@ namespace Galactic_Colors_Control_GUI /// public static class Program { + public static bool _dev = false; + public static bool _debug = false; /// /// The main entry point for the application. /// [STAThread] - static void Main() + private static void Main(string[] args) { - using (var game = new Game1()) + if (args.Length > 0) + { + switch (args[0]) + { + case "--debug": + _debug = true; + break; + + case "--dev": + _dev = true; + break; + + default: + Common.ConsoleWrite("Use --debug or --dev"); + break; + } + } + using (var game = new Game()) game.Run(); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/Properties/AssemblyInfo.cs b/Galactic Colors Control GUI/Properties/AssemblyInfo.cs index 66c2d21..a5affe2 100644 --- a/Galactic Colors Control GUI/Properties/AssemblyInfo.cs +++ b/Galactic Colors Control GUI/Properties/AssemblyInfo.cs @@ -1,36 +1,20 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Galactic Colors Control GUI")] [assembly: AssemblyProduct("Galactic Colors Control GUI")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("")] -[assembly: AssemblyCompany("sheychen")] -[assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("606d35be-02e8-4a7e-978e-04c2aca6ccd7")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.1.1")] -[assembly: AssemblyFileVersion("1.0.1.1")] +[assembly: Guid("606d35be-02e8-4a7e-978e-04c2aca6ccd7")] \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/ConnectState.cs b/Galactic Colors Control GUI/States/ConnectState.cs new file mode 100644 index 0000000..5f6dc35 --- /dev/null +++ b/Galactic Colors Control GUI/States/ConnectState.cs @@ -0,0 +1,154 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System.Threading; +using System; +using Galactic_Colors_Control_Common; + +namespace Galactic_Colors_Control_GUI.States +{ + public struct Message + { + public string title; + public string text; + public Message(string Title, string Text = "") + { + title = Title; + text = Text; + } + } + + public class ConnectState : State + { + private bool locked = false; + private bool showLoading = false; + private bool showOKMessage = false; + private bool showYNMessage = false; + + private Message message; + private string adress; + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + if (showLoading) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.multilang.Get("Loading", Game.singleton.config.lang), Game.singleton.fonts.basic); + } + else + { + if (showOKMessage) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic , null, Manager.textAlign.bottomCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("OK", Game.singleton.config.lang), Game.singleton.fonts.basic)) { locked = false; Game.singleton.GUI.ResetFocus(); showOKMessage = false; } + } + else + { + if (showYNMessage) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 100), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 100, 135, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Yes", Game.singleton.config.lang), Game.singleton.fonts.basic)) + { + if (!locked) + { + locked = true; + showYNMessage = false; + Game.singleton.GUI.ResetFocus(); + new Thread(ConnectHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 + 5, Game.singleton.ScreenHeight / 4 + 100, 135, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("No", Game.singleton.config.lang), Game.singleton.fonts.basic)) + { + showYNMessage = false; + Game.singleton.client.ResetHost(); + Game.singleton.GUI.ResetFocus(); + } + } + else + { + if (Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), ref adress, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, Game.singleton.multilang.Get("EnterHostname", Game.singleton.config.lang))) { + if (!locked) + { + locked = true; + new Thread(ValidateHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Connect", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + if (!locked) + { + locked = true; + new Thread(ValidateHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Back", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); } + Game.singleton.gameState = new MainMenuState(); + }).Start(); + } + } + } + } + } + } + + public override void Update() + { + Game.singleton.background.Update(); + } + + private void ValidateHost() + { + showLoading = true; + if (adress == null) { adress = ""; } + string Host = Game.singleton.client.ValidateHost(adress); + if (Host[0] == '*') + { + Host = Host.Substring(1); + message.title = Game.singleton.multilang.Get("Error", Game.singleton.config.lang); + message.text = Host; + showOKMessage = true; + Game.singleton.client.ResetHost(); + Game.singleton.logger.Write("Validate : " + Host, Logger.logType.info); + } + else + { + message.title = Game.singleton.multilang.Get("Use", Game.singleton.config.lang) + " " + Host + "?"; + showYNMessage = true; + } + showLoading = false; + locked = false; + } + + private void ConnectHost() + { + showLoading = true; + if (Game.singleton.client.ConnectHost()) + { + Game.singleton.logger.Write("Connected", Logger.logType.info); + Game.singleton.gameState = new IndentificationState(); + } + else + { + Game.singleton.logger.Write("Connect error", Logger.logType.error); + message.title = Game.singleton.multilang.Get("Error", Game.singleton.config.lang); + message.text = string.Empty; + showOKMessage = true; + Game.singleton.client.ResetHost(); + } + showLoading = false; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/GameState.cs b/Galactic Colors Control GUI/States/GameState.cs new file mode 100644 index 0000000..9437281 --- /dev/null +++ b/Galactic Colors Control GUI/States/GameState.cs @@ -0,0 +1,175 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System.Threading; +using System; +using Microsoft.Xna.Framework.Input; + +namespace Galactic_Colors_Control_GUI.States +{ + public class GameState : State + { + private bool showChat = false; + private string chatText; + private string chatInput; + + private bool showLoading = false; + private bool showOKMessage = false; + private Message message; + + public GameState() + { + Game.singleton.client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function + } + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Texture(new Rectangle(0, 0, Game.singleton.ScreenWidth, 30), Game.nullSprite, new MyMonoGame.Colors(new Color(0.1f, 0.1f, 0.1f))); + if (Game.singleton.GUI.Button(new Rectangle(5, 5, 50, 20), (showChat ? Game.singleton.multilang.Get("Hide", Game.singleton.config.lang) : Game.singleton.multilang.Get("Show", Game.singleton.config.lang)) + " " + Game.singleton.multilang.Get("Chat", Game.singleton.config.lang), Game.singleton.fonts.small, new MyMonoGame.Colors(Color.White, Color.LightGray, Color.Gray))) { Game.singleton.GUI.ResetFocus(); showChat = !showChat; } + + if (showChat) + { + Game.singleton.GUI.Box(new Rectangle(0, 30, 310, 310), Game.singleton.buttonsSprites[0]); + if (Game.singleton.GUI.TextField(new Rectangle(5, 35, 305, 20), ref chatInput, Game.singleton.fonts.basic, null, Manager.textAlign.centerLeft, Game.singleton.multilang.Get("EnterMessage", Game.singleton.config.lang))) { if (chatInput != null) { new Thread(ChatEnter).Start(); } } + Game.singleton.GUI.Label(new Rectangle(5, 60, 305, 245), chatText, Game.singleton.fonts.small, null, Manager.textAlign.topLeft, true); + } + + if (showLoading) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.multilang.Get("Loading", Game.singleton.config.lang), Game.singleton.fonts.basic); + } + else + { + if (showOKMessage) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("OK", Game.singleton.config.lang), Game.singleton.fonts.basic)) { Game.singleton.GUI.ResetFocus(); showOKMessage = false; Game.singleton.client.ExitHost(); } + } + } + } + + public override void Update() + { + if (Keyboard.GetState().IsKeyDown(Keys.Escape) || (!Game.singleton.client.isRunning)) { + Game.singleton.client.ExitHost(); + Game.singleton.gameState = new MainMenuState(); + } + } + + private void ChatEnter() + { + string request = chatInput; + chatInput = null; + + if (request == null) + return; + + if (request.Length == 0) + return; + + ResultData res; + if (request[0] == Game.singleton.config.commandChar) + { + request = request.Substring(1); + res = Game.singleton.client.Request(Common.SplitArgs(request)); + ChatText(Game.singleton.multilang.GetResultText(res, Game.singleton.config.lang)); + } + else + { + res = Game.singleton.client.Request(Common.Strings("say", request)); + if (res.type != ResultTypes.OK) + { + ChatText(Game.singleton.multilang.GetResultText(res, Game.singleton.config.lang)); + } + } + } + + private void OnEvent(object sender, EventArgs e) + { + //TODO add PartyKick + EventData eve = ((EventDataArgs)e).Data; + if (eve.type == EventTypes.ServerKick) + { + Game.singleton.logger.Write("Server kick" + eve.data, Logger.logType.warm); + message.title = Game.singleton.multilang.Get("ServerKick", Game.singleton.config.lang); + message.text = Common.ArrayToString(eve.data); + showOKMessage = true; + }else + { + ChatText(Game.singleton.multilang.GetEventText(eve, Game.singleton.config.lang)); + } + } + + public void ChatText(string text) + { + chatText += (text + Environment.NewLine); + } + + /* + private void PartyClick() + { + showLoading = true; + GUI.ResetFocus(); + //TODO + /* + if (showParty) + { + client.SendRequest("/party leave"); + showParty = false; + showLoading = false; + } + else + { + client.Output.Clear(); + client.SendRequest("/party list"); + int wait = 0; + while (wait < 20) + { + if (client.Output.Count > 0) + { + wait = 20; + } + else + { + wait++; + Thread.Sleep(200); + } + } + if (client.Output.Count > 0) + { + Thread.Sleep(500); + if (client.Output.Count > 1) + { + messageTitle = "Party"; + messageText = string.Empty; + foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } + showOKMessage = true; + client.Output.Clear(); + } + else + { + messageTitle = "Any party"; + messageText = string.Empty; + foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } + showOKMessage = true; + client.Output.Clear(); + } + } + else + { + messageTitle = "Timeout"; + messageText = ""; + showOKMessage = true; + showLoading = false; + client.Output.Clear(); + } + } + }*/ + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/IndentificationState.cs b/Galactic Colors Control GUI/States/IndentificationState.cs new file mode 100644 index 0000000..54551c6 --- /dev/null +++ b/Galactic Colors Control GUI/States/IndentificationState.cs @@ -0,0 +1,102 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System.Threading; +using System; +using Galactic_Colors_Control_Common.Protocol; +using Galactic_Colors_Control_Common; + +namespace Galactic_Colors_Control_GUI.States +{ + public class IndentificationState : State + { + private string username; + private Message message; + + private bool locked = false; + private bool showLoading = false; + private bool showOKMessage = false; + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title , new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + if (showLoading) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.multilang.Get("Loading", Game.singleton.config.lang), Game.singleton.fonts.basic); + } + else + { + if (showOKMessage) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("OK", Game.singleton.config.lang), Game.singleton.fonts.basic)){ Game.singleton.GUI.ResetFocus(); showOKMessage = false; } + } + else + { + if (Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), ref username, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, Game.singleton.multilang.Get("Username", Game.singleton.config.lang))) { + if (!locked) + { + locked = true; + new Thread(IdentifiacateHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Validate", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) { + if (!locked) + { + locked = true; + new Thread(IdentifiacateHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Back", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + Game.singleton.client.ExitHost(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); } + Game.singleton.gameState = new MainMenuState(); + }).Start(); + } + } + } + } + } + + private void IdentifiacateHost() + { + showLoading = true; + if (username != null) + { + if (username.Length > 3) + { + ResultData res = Game.singleton.client.Request(new string[2] { "connect", username }); + if (res.type == ResultTypes.OK) + { + Game.singleton.gameState = new PartyState(); + } + else + { + message.title = Game.singleton.multilang.Get("Error", Game.singleton.config.lang); + message.text = Common.ArrayToString(res.result); + showOKMessage = true; + } + } + } + showLoading = false; + locked = false; + } + + + public override void Update() + { + Game.singleton.background.Update(); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/MainMenuState.cs b/Galactic Colors Control GUI/States/MainMenuState.cs new file mode 100644 index 0000000..cac61b7 --- /dev/null +++ b/Galactic Colors Control GUI/States/MainMenuState.cs @@ -0,0 +1,64 @@ +using System; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework; +using MyMonoGame.GUI; +using System.Reflection; +using Galactic_Colors_Control; +using System.Threading; +using Galactic_Colors_Control_Common; + +namespace Galactic_Colors_Control_GUI.States +{ + public class MainMenuState : State + { + public static Texture2D logoSprite; + private bool locked = false; + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 40), Game.singleton.multilang.Get("GUI", Game.singleton.config.lang) + " " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth - 64, Game.singleton.ScreenHeight - 74, 64, 64), logoSprite)) { System.Diagnostics.Process.Start("https://sheychen.shost.ca/"); } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Play", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Green))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + Game.singleton.client = new Client(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 5, 0.1)) { Thread.Sleep(20); } + Game.singleton.gameState = new ConnectState(); + }).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Options", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Blue))) { + Game.singleton.GUI.ResetFocus(); + Game.singleton.gameState = new OptionsState(); + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Exit", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Red))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + Game.singleton.logger.Write("Game exit", Logger.logType.warm); + Game.singleton.gameState = new TitleState(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 0, 0.1)) { Thread.Sleep(50); } + Game.singleton.logger.Join(); + Game.singleton.Exit(); + }).Start(); + } + } + } + + public override void Update() + { + Game.singleton.background.Update(); + } + } +} diff --git a/Galactic Colors Control GUI/States/OptionsState.cs b/Galactic Colors Control GUI/States/OptionsState.cs new file mode 100644 index 0000000..6fbdc0f --- /dev/null +++ b/Galactic Colors Control GUI/States/OptionsState.cs @@ -0,0 +1,54 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System.Threading; + +namespace Galactic_Colors_Control_GUI.States +{ + public class OptionsState : State + { + private bool locked = false; + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Langs[Game.singleton.config.lang], Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) { + + Game.singleton.GUI.ResetFocus(); + ChangeLang(); + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Back", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + Game.singleton.config.Save(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); } + Game.singleton.gameState = new MainMenuState(); + }).Start(); + } + } + } + + public override void Update() + { + Game.singleton.background.Update(); + } + + private void ChangeLang() + { + if (Game.singleton.config.lang < Game.singleton.multilang.Langs.Count - 1) + { + Game.singleton.config.lang++; + } + else + { + Game.singleton.config.lang = 0; + } + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/PartyState.cs b/Galactic Colors Control GUI/States/PartyState.cs new file mode 100644 index 0000000..fe84d9b --- /dev/null +++ b/Galactic Colors Control GUI/States/PartyState.cs @@ -0,0 +1,166 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System.Threading; +using System; +using Galactic_Colors_Control_Common.Protocol; +using Galactic_Colors_Control_Common; +using System.Collections.Generic; + +namespace Galactic_Colors_Control_GUI.States +{ + public class PartyState : State + { + public struct Party + { + public int id; + public string text; + + public Party(int ID, string TEXT) + { + id = ID; + text = TEXT; + } + } + + private string password; + private int page = 1; + private List parties = new List(); + private Message message; + private int id = -1; + + private bool locked = false; + private bool showLoading = false; + private bool showOKMessage = false; + + public PartyState() + { + UpdateParty(); + } + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + if (showLoading) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.multilang.Get("Loading", Game.singleton.config.lang), Game.singleton.fonts.basic); + } + else + { + if (showOKMessage) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("OK", Game.singleton.config.lang), Game.singleton.fonts.basic)) { Game.singleton.GUI.ResetFocus(); showOKMessage = false; } + } + else + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 2 - 300, 300, 600), Game.singleton.buttonsSprites[0]); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 2 - 290, 100, 40), Game.singleton.buttonsSprites[0] ,Game.singleton.multilang.Get("Update", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + if (!locked) + { + locked = true; + new Thread(UpdateParty).Start(); + } + } + Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 + 40, Game.singleton.ScreenHeight / 2 - 290, 100, 40), ref password, Game.singleton.fonts.basic, null, Manager.textAlign.centerCenter, Game.singleton.multilang.Get("Password", Game.singleton.config.lang)); + if (parties.Count > 0) { + if (parties.Count > 10) { + //TODO page change + } + for (int i = (page - 1) * 10; i < page * 10 && i < parties.Count; i++) + { + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 100, Game.singleton.ScreenHeight / 2 - 250 + i*50, 200, 40), Game.singleton.buttonsSprites[0], parties[i].text, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + locked = true; + id = parties[i].id; + new Thread(PartyJoin).Start(); + } + } + } + else + { + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 2 - 240), Game.singleton.multilang.Get("AnyParty", Game.singleton.config.lang), Game.singleton.fonts.basic, null, Manager.textAlign.centerCenter); + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 250, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Back", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + Game.singleton.client.ExitHost(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); } + Game.singleton.gameState = new MainMenuState(); + }).Start(); + } + } + } + } + } + + private void UpdateParty() + { + showLoading = true; + page = 1; + ResultData res = Game.singleton.client.Request(new string[2] { "party", "list" }); + if (res.type == ResultTypes.OK) { + parties.Clear(); + foreach (string str in res.result) + { + string[] data = str.Split(new char[1] { ':' }, 2); + int id = -1; + if (int.TryParse(data[0], out id)) + { + parties.Add(new Party(id, data[1])); + } + } + } + else + { + parties = new List(); + } + showLoading = false; + locked = false; + } + + private void PartyJoin() + { + showLoading = true; + if (id != -1) + { + string[] request = password != null ? new string[4] { "party", "join", id.ToString() , password } : new string[3] { "party", "join", id.ToString() }; + ResultData res = Game.singleton.client.Request(request); + if (res.type == ResultTypes.OK) + { + Game.singleton.logger.Write("Join party " + id.ToString(), Logger.logType.info); + Game.singleton.gameState = new GameState(); + } + else + { + Game.singleton.logger.Write("Join error " + res.result, Logger.logType.error); + message.title = Game.singleton.multilang.Get("Error", Game.singleton.config.lang); + message.text = Common.ArrayToString(res.result); + showOKMessage = true; + } + } + showLoading = false; + locked = false; + } + + private void PartyCreate() + { + //TODO + } + + public override void Update() + { + Game.singleton.background.Update(); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/State.cs b/Galactic Colors Control GUI/States/State.cs new file mode 100644 index 0000000..294cd2f --- /dev/null +++ b/Galactic Colors Control GUI/States/State.cs @@ -0,0 +1,20 @@ +using Microsoft.Xna.Framework.Graphics; + +namespace Galactic_Colors_Control_GUI.States +{ + /// + /// Game Menu Main Class + /// + public class State + { + public virtual void Draw(SpriteBatch spritebatch) + { + + } + + public virtual void Update() + { + + } + } +} diff --git a/Galactic Colors Control GUI/States/TitleState.cs b/Galactic Colors Control GUI/States/TitleState.cs new file mode 100644 index 0000000..a9c2ad9 --- /dev/null +++ b/Galactic Colors Control GUI/States/TitleState.cs @@ -0,0 +1,41 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System; + +namespace Galactic_Colors_Control_GUI.States +{ + /// + /// Only title in screen (and state change) + /// + public class TitleState : State + { + private DateTime _changeDate; + private State _target; + + public TitleState() + { + _target = null; + } + + public TitleState(State target, TimeSpan time) + { + _target = target; + _changeDate = DateTime.Now.Add(time); + } + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 2), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + } + + public override void Update() + { + if (_target != null) + { + if (DateTime.Now > _changeDate) { Game.singleton.gameState = _target; } + } + } + } +} diff --git a/Galactic Colors Control GUI/Utilities.cs b/Galactic Colors Control GUI/Utilities.cs index da28d29..9dca3de 100644 --- a/Galactic Colors Control GUI/Utilities.cs +++ b/Galactic Colors Control GUI/Utilities.cs @@ -1,11 +1,24 @@ using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; +using System; using System.IO; namespace Galactic_Colors_Control_GUI { - static class Utilities + public struct Fonts { + public SpriteFont small; //Text fonts + public SpriteFont basic; + public SpriteFont title; + } + + internal static class Utilities + { + /// + /// Load Texture2D from files + /// + /// File .png path + /// Result sprite static public void SpriteFromPng(string path, ref Texture2D sprite, GraphicsDevice graphics) { if (File.Exists(path)) @@ -17,6 +30,11 @@ namespace Galactic_Colors_Control_GUI } } + /// + /// Load SoundEffect from files + /// + /// File .mp3 path + /// Result sound static public void SoundFromMp3(string path, ref SoundEffect sound) { if (File.Exists(path)) @@ -27,5 +45,18 @@ namespace Galactic_Colors_Control_GUI } } } + + public static bool DoubleTo(ref double value, double target, double speed) + { + speed = Math.Abs(speed); + bool up = value < target; + value += (up ? 1 : -1) * speed; + if ((up && value >= target) || (!up && value <= target)) + { + value = target; + return true; + } + return false; + } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/App.config b/Galactic Colors Control Server/App.config index d1428ad..5035d4f 100644 --- a/Galactic Colors Control Server/App.config +++ b/Galactic Colors Control Server/App.config @@ -1,6 +1,6 @@ - - - - + + + + \ No newline at end of file diff --git a/Galactic Colors Control Server/Client.cs b/Galactic Colors Control Server/Client.cs new file mode 100644 index 0000000..b20ad5f --- /dev/null +++ b/Galactic Colors Control Server/Client.cs @@ -0,0 +1,14 @@ +namespace Galactic_Colors_Control_Server +{ + public class Client + { + public int status = -1; + public string pseudo = ""; + public int partyID = -1; + + public Party party + { + get { if (partyID != -1) { return Program.parties[partyID]; } else { return null; } } + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/BroadcastCommand.cs b/Galactic Colors Control Server/Commands/BroadcastCommand.cs new file mode 100644 index 0000000..b3df2ff --- /dev/null +++ b/Galactic Colors Control Server/Commands/BroadcastCommand.cs @@ -0,0 +1,26 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class BroadcastCommand : ICommand + { + public string DescText { get { return "Sends message to all clients."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } + public string HelpText { get { return "Use 'broadcast [text]' to send message to all clients."; } } + public bool IsClient { get { return false; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public bool IsServer { get { return true; } } + public int maxArgs { get { return 1; } } + public int minArgs { get { return 1; } } + public string Name { get { return "broadcast"; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + Utilities.Broadcast(new EventData(EventTypes.ChatMessage, Common.Strings("Server : " + args[1]))); + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ClearCommand.cs b/Galactic Colors Control Server/Commands/ClearCommand.cs index 98e9dba..71bbcf0 100644 --- a/Galactic Colors Control Server/Commands/ClearCommand.cs +++ b/Galactic Colors Control Server/Commands/ClearCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,8 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "clear"; } } public string DescText { get { return "Clears the console screen."; } } - public string HelpText { get { return "Use /clear to execute Console.Clear()."; } } + public string HelpText { get { return "Use 'clear' to execute Console.Clear()."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } public bool IsClientSide { get { return true; } } @@ -15,10 +18,18 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - Console.Clear(); - Console.Write(">"); + if (server) + { + Console.Clear(); + Console.Write(">"); + return new RequestResult(ResultTypes.OK); + } + else + { + return new RequestResult(ResultTypes.Error, Common.Strings("ClientSide")); + } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/CountCommand.cs b/Galactic Colors Control Server/Commands/Client/CountCommand.cs new file mode 100644 index 0000000..1a32726 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Client/CountCommand.cs @@ -0,0 +1,25 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class ClientCountCommand : ICommand + { + public string Name { get { return "count"; } } + public string DescText { get { return "Counts connected clients."; } } + public string HelpText { get { return "Use 'client count' to show connected clients count and size"; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + return new RequestResult(ResultTypes.OK, Common.Strings(Program.clients.Count.ToString(), Program.config.size.ToString())); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/KickCommand.cs b/Galactic Colors Control Server/Commands/Client/KickCommand.cs new file mode 100644 index 0000000..1fea922 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Client/KickCommand.cs @@ -0,0 +1,43 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class ClientKickCommand : ICommand + { + public string Name { get { return "kick"; } } + public string DescText { get { return "Kicks selected client."; } } + public string HelpText { get { return "Use 'client kick [username] ' to kick client from server."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return false; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return true; } } + public int minArgs { get { return 1; } } + public int maxArgs { get { return 2; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + Socket target = null; + foreach (Socket client in Program.clients.Keys) + { + if (Utilities.GetName(client) == args[2]) { target = client; } + } + if (target == null) + return new RequestResult(ResultTypes.Error, Common.Strings("CantFind")); + + Program.logger.Write(args[2] + " was kick by server.", Logger.logType.info, Logger.logConsole.show); + if (args.Length > 2) + { + Utilities.Send(target, new EventData(EventTypes.ServerKick, Common.Strings(args[3]))); + Program.logger.Write("because" + args[3], Logger.logType.debug); + } + else + { + Utilities.Send(target, new EventData(EventTypes.ServerKick)); + } + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/ListCommand.cs b/Galactic Colors Control Server/Commands/Client/ListCommand.cs new file mode 100644 index 0000000..dbea879 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Client/ListCommand.cs @@ -0,0 +1,45 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class ClientListCommand : ICommand + { + public string Name { get { return "list"; } } + public string DescText { get { return "Lists connected clients."; } } + public string HelpText { get { return "Use 'client list' to display all connected client username or IP."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if (server) + { + string text = " "; + foreach (Socket socket in Program.clients.Keys) + { + text += (Utilities.GetName(socket) + ", "); + } + text = text.Remove(text.Length - 2, 2); + return new RequestResult(ResultTypes.OK, Common.Strings(text)); + } + else + { + string[] data = new string[Program.clients.Count]; + int i = 0; + foreach (Socket socket in Program.clients.Keys) + { + data[i] = (Utilities.GetName(socket) + ", "); + i++; + } + return new RequestResult(ResultTypes.OK, data); + } + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/StatusCommand.cs b/Galactic Colors Control Server/Commands/Client/StatusCommand.cs new file mode 100644 index 0000000..9ef53a1 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Client/StatusCommand.cs @@ -0,0 +1,42 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; +using System.Net; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class ClientStatusCommand : ICommand + { + public string Name { get { return "status"; } } + public string DescText { get { return "Get client status."; } } + public string HelpText { get { return "Use 'client status [username]' to show client status."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return false; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 1; } } + public int maxArgs { get { return 1; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + Socket target = null; + foreach (Socket client in Program.clients.Keys) + { + if (Utilities.GetName(client) == args[2]) { target = client; } + } + if (target == null) + return new RequestResult(ResultTypes.Error, Common.Strings("CantFind")); + + string text = ""; + text += ("Name : " + Utilities.GetName(target) + Environment.NewLine); + text += ("IP : " + ((IPEndPoint)target.LocalEndPoint).Address.ToString() + Environment.NewLine); + if (Program.clients[target].party != null) + { + text += ("Party : " + Program.clients[target].party + Environment.NewLine); + } + return new RequestResult(ResultTypes.OK, Common.Strings(text)); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/CloseCommand.cs b/Galactic Colors Control Server/Commands/CloseCommand.cs deleted file mode 100644 index 9129e77..0000000 --- a/Galactic Colors Control Server/Commands/CloseCommand.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Net.Sockets; - -namespace Galactic_Colors_Control_Server.Commands -{ - public class CloseCommand : ICommand - { - public string Name { get { return "close"; } } - public string DescText { get { return "Closes server from connections."; } } - public string HelpText { get { return "Use /close to stop connection process"; } } - public bool IsServer { get { return true; } } - public bool IsClient { get { return false; } } - public bool IsClientSide { get { return false; } } - public bool IsNoConnect { get { return false; } } - public int minArgs { get { return 0; } } - public int maxArgs { get { return 0; } } - - public void Execute(string[] args, Socket soc, bool server = false) - { - if (Program._open) - { - Program._open = false; - Logger.Write("Server closed", Logger.logType.warm); - } - else - { - Utilities.ConsoleWrite("Server already close"); - } - } - } -} diff --git a/Galactic Colors Control Server/Commands/ConnectCommand.cs b/Galactic Colors Control Server/Commands/ConnectCommand.cs index 03e36ce..54bf0ab 100644 --- a/Galactic Colors Control Server/Commands/ConnectCommand.cs +++ b/Galactic Colors Control Server/Commands/ConnectCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net; using System.Net.Sockets; @@ -8,7 +9,8 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "connect"; } } public string DescText { get { return "Gets an username."; } } - public string HelpText { get { return "Use /connect [username] to start identification"; } } + public string HelpText { get { return "Use 'connect [username]' to start identification"; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return false; } } public bool IsClient { get { return true; } } public bool IsClientSide { get { return false; } } @@ -16,34 +18,29 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 1; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (!Utilities.IsConnect(soc)) + if (Utilities.IsConnect(soc)) + return new RequestResult(ResultTypes.Error, Common.Strings("Connected")); + + if (args[1].Length < 3) + return new RequestResult(ResultTypes.Error, Common.Strings("TooShort")); + + Program.logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug); + bool allreadyconnected = false; + args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1); + foreach (Client client in Program.clients.Values) { - Logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug); - bool allreadyconnected = false; - foreach(Data client in Program.clients.Values) - { - if(client.pseudo == args[1]) { allreadyconnected = true; break; } - } - if (!allreadyconnected) - { - Program.clients[soc].status = 0; - //args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1); - Program.clients[soc].pseudo = args[1]; - Utilities.Send(soc, "/connected", Utilities.dataType.message); - Utilities.Broadcast(args[1] + " joined the server", Utilities.dataType.message); - Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info); - } - else - { - Utilities.Send(soc, "/allreadytaken", Utilities.dataType.message); - } - } - else - { - Utilities.Send(soc, "You are allready " + Utilities.GetName(soc), Utilities.dataType.message); + if (client.pseudo == args[1]) { allreadyconnected = true; break; } } + if (allreadyconnected) + return new RequestResult(ResultTypes.Error, Common.Strings("AllreadyTaken")); + + Program.clients[soc].status = 0; + Program.clients[soc].pseudo = args[1]; + Utilities.Broadcast(new EventData(EventTypes.ServerJoin, Common.Strings(args[1]))); + Program.logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info); + return new RequestResult(ResultTypes.OK, Common.Strings(args[1])); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/CountCommand.cs b/Galactic Colors Control Server/Commands/CountCommand.cs deleted file mode 100644 index e650b93..0000000 --- a/Galactic Colors Control Server/Commands/CountCommand.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Net.Sockets; - -namespace Galactic_Colors_Control_Server.Commands -{ - public class CountCommand : ICommand - { - public string Name { get { return "count"; } } - public string DescText { get { return "Counts connected clients."; } } - public string HelpText { get { return "Use /count to show connected clients count and size"; } } - public bool IsServer { get { return true; } } - public bool IsClient { get { return false; } } - public bool IsClientSide { get { return false; } } - public bool IsNoConnect { get { return false; } } - public int minArgs { get { return 0; } } - public int maxArgs { get { return 0; } } - - public void Execute(string[] args, Socket soc, bool server = false) - { - Utilities.ConsoleWrite(Program.clients.Count + "/" + Program.config.size); - } - } -} diff --git a/Galactic Colors Control Server/Commands/ExitCommand.cs b/Galactic Colors Control Server/Commands/ExitCommand.cs index 55be0bb..ba5d03e 100644 --- a/Galactic Colors Control Server/Commands/ExitCommand.cs +++ b/Galactic Colors Control Server/Commands/ExitCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -6,33 +7,27 @@ namespace Galactic_Colors_Control_Server.Commands public class ExitCommand : ICommand { public string Name { get { return "exit"; } } - public string DescText { get { return "Leave the program."; } } - public string HelpText { get { return "Use /exit to stop actual program."; } } - public bool IsServer { get { return true; } } + public string DescText { get { return "Leave the server."; } } + public string HelpText { get { return "Use 'exit' to stop actual program."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } + public bool IsServer { get { return false; } } public bool IsClient { get { return true; } } public bool IsClientSide { get { return false; } } public bool IsNoConnect { get { return true; } } public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (server) - { - Program._run = false; - Utilities.ConsoleWrite("Exit server"); - } - else - { - soc.Shutdown(SocketShutdown.Both); - Logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info); - string username = Utilities.GetName(soc); - bool connected = Program.clients[soc].status != -1; - soc.Close(); - Program.clients.Remove(soc); - if (connected) { Utilities.Broadcast(username + " leave the server", Utilities.dataType.message); } - Logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug); - } + soc.Shutdown(SocketShutdown.Both); + Program.logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info); + string username = Utilities.GetName(soc); + bool connected = Program.clients[soc].status != -1; + soc.Close(); + Program.clients.Remove(soc); + if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } + Program.logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/HelpCommand.cs b/Galactic Colors Control Server/Commands/HelpCommand.cs index 0e8a419..4169c46 100644 --- a/Galactic Colors Control Server/Commands/HelpCommand.cs +++ b/Galactic Colors Control Server/Commands/HelpCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; @@ -9,54 +11,68 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "help"; } } public string DescText { get { return "Shows the help."; } } - public string HelpText { get { return "Use /help [command] to display command help."; } } + public string HelpText { get { return "Use 'help [command]' to display command help. ('hell -all' for full help)"; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } public bool IsClientSide { get { return false; } } public bool IsNoConnect { get { return false; } } public int minArgs { get { return 0; } } - public int maxArgs { get { return 1; } } + public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if(args.Length == 1) + bool isGroup = false; + bool isAll = false; + if (args.Length == 2) + { + isGroup = Enum.GetNames(typeof(Manager.CommandGroup)).Contains(args[1]); + isAll = (args[1] == "-all"); + } + if (args.Length == 1 || (isGroup || isAll)) { - List list = new List(); int maxLen = 0; - foreach (string com in Manager.commands.Keys) + List list = new List(); + foreach (ICommand com in Manager.commands) { - if(Manager.CanAccess(Manager.commands[com], soc, server)) + if (Manager.CanAccess(com, soc, server)) { - list.Add(com); - if(com.Length > maxLen) { maxLen = com.Length; } + if (!isGroup || (isGroup && com.Group == (Manager.CommandGroup)Enum.Parse(typeof(Manager.CommandGroup), args[1]))) + { + list.Add(com); + if (com.Name.Length + (com.Group == 0 ? 0 : 4) > maxLen) { maxLen = com.Name.Length + (com.Group == 0 ? 0 : 4); } + } } } - list.Sort(); - string text = "Use /help [command] for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine; - foreach (var key in list) + list.Sort((x, y) => x.Group.CompareTo(y.Group)); + string text = "Use 'help [command]' for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine; + Manager.CommandGroup actualGroup = 0; + foreach (ICommand com in list) { - text += (" " + key + new string(' ', maxLen - key.Length) + " : " + Manager.commands[key].DescText + Environment.NewLine); + if (com.Group != actualGroup) + { + text += (Environment.NewLine + " " + com.Group.ToString() + Environment.NewLine + ((isGroup || isAll) ? "" : (" Use 'help " + com.Group.ToString() + "'"))); + actualGroup = com.Group; + } + if ((!(isGroup || isAll) && com.Group == 0) || (isGroup || isAll)) + { + text += (" " + (com.Group != 0 ? new string(' ', 4) : "") + com.Name + new string(' ', maxLen - com.Name.Length - (com.Group == 0 ? 0 : 4)) + " : " + com.DescText + Environment.NewLine); + } } - Utilities.Return(text, soc, server); + return new RequestResult(ResultTypes.OK, Common.Strings(text)); } else { - if (Manager.commands.ContainsKey(args[1])) - { - if (Manager.CanAccess(Manager.commands[args[1]], soc, server)) - { - Utilities.Return(Manager.commands[args[1]].HelpText, soc, server); - } - else - { - Utilities.Return("Any help for " + args[1], soc, server); - } - } - else - { - Utilities.Return("Any help for " + args[1], soc, server); - } + ICommand command = null; + args = args.Skip(1).ToArray(); + if (!Manager.TryGetCommand(args, ref command)) + return new RequestResult(ResultTypes.Error, Common.Strings("AnyCommand")); + + if (!Manager.CanAccess(command, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("AnyCommand")); + + return new RequestResult(ResultTypes.OK, Common.Strings(command.HelpText)); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ICommand.cs b/Galactic Colors Control Server/Commands/ICommand.cs index 63cb3c8..f68f293 100644 --- a/Galactic Colors Control Server/Commands/ICommand.cs +++ b/Galactic Colors Control Server/Commands/ICommand.cs @@ -1,4 +1,5 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -7,6 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands string Name { get; } string DescText { get; } string HelpText { get; } + Manager.CommandGroup Group { get; } bool IsServer { get; } bool IsClient { get; } bool IsClientSide { get; } @@ -14,6 +16,6 @@ namespace Galactic_Colors_Control_Server.Commands int minArgs { get; } int maxArgs { get; } - void Execute(string[] args, Socket soc = null, bool server = false); + RequestResult Execute(string[] args, Socket soc = null, bool server = false); } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/KickCommand.cs b/Galactic Colors Control Server/Commands/KickCommand.cs deleted file mode 100644 index ac7a75b..0000000 --- a/Galactic Colors Control Server/Commands/KickCommand.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Sockets; - -namespace Galactic_Colors_Control_Server.Commands -{ - public class KickCommand : ICommand - { - public string Name { get { return "kick"; } } - public string DescText { get { return "Kicks selected client."; } } - public string HelpText { get { return "Use /kick [username] to kick client from server."; } } - public bool IsServer { get { return true; } } - public bool IsClient { get { return false; } } - public bool IsClientSide { get { return false; } } - public bool IsNoConnect { get { return true; } } - public int minArgs { get { return 1; } } - public int maxArgs { get { return 2; } } - - public void Execute(string[] args, Socket soc, bool server = false) - { - Socket target = null; - foreach(Socket client in Program.clients.Keys) - { - if(Utilities.GetName(client) == args[1]) { target = client; } - } - if (target != null) - { - Logger.Write(args[1] + " was kick by server.", Logger.logType.info); - if (args.Length > 2) - { - Utilities.Send(target, "/kick " + args[2], Utilities.dataType.message); - Logger.Write("because" + args[1], Logger.logType.debug); - } - else { - Utilities.Send(target, "/kick", Utilities.dataType.message); - } - } - else - { - Utilities.Return("Can't find " + args[1], soc, server); - } - } - } -} diff --git a/Galactic Colors Control Server/Commands/ListCommand.cs b/Galactic Colors Control Server/Commands/ListCommand.cs deleted file mode 100644 index 244fa6a..0000000 --- a/Galactic Colors Control Server/Commands/ListCommand.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Net.Sockets; - -namespace Galactic_Colors_Control_Server.Commands -{ - public class ListCommand : ICommand - { - public string Name { get { return "list"; } } - public string DescText { get { return "Lists connected clients."; } } - public string HelpText { get { return "Use /list to display all connected client username or IP."; } } - public bool IsServer { get { return true; } } - public bool IsClient { get { return false; } } - public bool IsClientSide { get { return false; } } - public bool IsNoConnect { get { return false; } } - public int minArgs { get { return 0; } } - public int maxArgs { get { return 0; } } - - public void Execute(string[] args, Socket soc, bool server = false) - { - string text = " "; - foreach (Socket socket in Program.clients.Keys) - { - text += (Utilities.GetName(socket) + ", "); - } - text = text.Remove(text.Length - 2, 2); - Utilities.ConsoleWrite(text); - } - } -} diff --git a/Galactic Colors Control Server/Commands/LogLevelCommand.cs b/Galactic Colors Control Server/Commands/LogLevelCommand.cs index 87b3055..04caa7c 100644 --- a/Galactic Colors Control Server/Commands/LogLevelCommand.cs +++ b/Galactic Colors Control Server/Commands/LogLevelCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,8 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "loglevel"; } } public string DescText { get { return "Change console loglevel."; } } - public string HelpText { get { return "Use /loglevel [loglevel] to change Loglevel."; } } + public string HelpText { get { return "Use 'loglevel [loglevel]' to change Loglevel. (dev ,debug, info, warm, error, fatal)"; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } public bool IsClientSide { get { return true; } } @@ -15,16 +18,17 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 1; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { if (Enum.TryParse(args[1], true, out Program.config.logLevel)) { - Utilities.ConsoleWrite("LogLevel: " + Program.config.logLevel.ToString()); + Program.logger.ChangeLevel(Program.config.logLevel); + return new RequestResult(ResultTypes.OK, Common.Strings(Program.config.logLevel.ToString())); } else { - Utilities.ConsoleWrite("Incorrect argument (debug, info, important, error, fatal)"); + return new RequestResult(ResultTypes.Error, Common.Strings("IncorrectArgs")); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Manager.cs b/Galactic Colors Control Server/Commands/Manager.cs index aaa773f..35eea72 100644 --- a/Galactic Colors Control Server/Commands/Manager.cs +++ b/Galactic Colors Control Server/Commands/Manager.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; @@ -6,9 +8,13 @@ using System.Reflection; namespace Galactic_Colors_Control_Server.Commands { - class Manager + public class Manager { - public static Dictionary commands { get; private set; } = new Dictionary(); + public static List commands { get; private set; } = new List(); + + public enum CommandGroup { root, server, party, client } + + private static RequestResult AnyCommand = new RequestResult(ResultTypes.Error, Common.Strings("AnyCommand")); /// /// Find all ICommand and add them to commands @@ -19,8 +25,8 @@ namespace Galactic_Colors_Control_Server.Commands IEnumerable coms = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.GetInterfaces().Contains(typeof(ICommand)) && x.GetConstructor(Type.EmptyTypes) != null).Select(x => Activator.CreateInstance(x) as ICommand); foreach (ICommand com in coms) { - commands.Add(com.Name, com); - Logger.Write("Added command " + com.GetType().Name, Logger.logType.debug); + commands.Add(com); + Program.logger.Write("Added command " + com.Group.ToString() + " " + com.Name, Logger.logType.debug); } } @@ -30,45 +36,97 @@ namespace Galactic_Colors_Control_Server.Commands /// command with args /// Sender socket /// Is server? - public static void Execute(string[] args, Socket soc = null, bool server = false) + public static RequestResult Execute(string[] args, Socket soc = null, bool server = false) { - if (commands.ContainsKey(args[0])) - { - ICommand command = commands[args[0]]; - if (CanAccess(command, soc, server)) - { - if (command.IsClientSide) - { - Utilities.Return("It's a client side command", soc, server); - } - else - { - if (args.Length > command.minArgs) - { - if (args.Length - 1 <= command.maxArgs) - { - command.Execute(args, soc, server); - } - else - { - Utilities.Return("Command " + command.Name + " require at most " + command.minArgs + " argument(s).", soc, server); - } - } + ICommand command = null; + if (!TryGetCommand(args, ref command)) + return AnyCommand; - else - { - Utilities.Return("Command " + command.Name + " require at least " + command.minArgs + " argument(s).", soc, server); - } + if (!CanAccess(command, soc, server)) + return AnyCommand; + + if (!server && command.IsClientSide) + return new RequestResult(ResultTypes.Error, Common.Strings("ClientSide")); + + if (args.Length - (command.Group == 0 ? 0 : 1) <= command.minArgs) + return new RequestResult(ResultTypes.Error, new string[2] { "TooShort", command.minArgs.ToString() }); + + if (args.Length - (command.Group == 0 ? 1 : 2) > command.maxArgs) + return new RequestResult(ResultTypes.Error, new string[2] { "TooLong", command.maxArgs.ToString() }); + + try + { + return command.Execute(args, soc, server); + } + catch (Exception e) + { + Program.logger.Write("Command " + args[0] + " Exception : " + e.Message, Logger.logType.error); + return new RequestResult(ResultTypes.Error, Common.Strings("ExecuteException")); + } + } + + public static string CommandToString(ICommand command) + { + string text = ""; + if (command.Group != 0) { text += (command.Group.ToString() + " "); } + text += command.Name; + return text; + } + + /// + /// Convert command args in readable string + /// + /// Command args + public static string CommandToString(string[] args) + { + if (args.Length > 0) + { + string text = ""; + foreach (string arg in args) + { + text += (arg + " "); + } + return text; + } + else + { + return null; + } + } + + /// + /// Try to get a command + /// + /// command args + /// Command result + /// Correct command + public static bool TryGetCommand(string[] args, ref ICommand command) + { + if (args.Length > 0) + { + List groups = Enum.GetNames(typeof(CommandGroup)).ToList(); + CommandGroup group = 0; + if (groups.Contains(args[0])) + { + if (args.Length > 1) + { + group = (CommandGroup)Enum.Parse(typeof(CommandGroup), args[0]); } } + IEnumerable coms = commands.Where(p => (p.Name == args[group == 0 ? 0 : 1] && p.Group == group)); + if (coms.Count() == 1) + { + command = coms.First(); + return true; + } else { - Utilities.Return("Unknown command : " + args[0], soc, server); + return false; } } else { - Utilities.Return("Unknown command : " + args[0], soc, server); + return false; } } @@ -85,7 +143,7 @@ namespace Galactic_Colors_Control_Server.Commands { if (command.IsClient) { - if(!Utilities.IsConnect(soc)) + if (!Utilities.IsConnect(soc)) { return command.IsNoConnect; } @@ -101,4 +159,4 @@ namespace Galactic_Colors_Control_Server.Commands } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/OpenCommand.cs b/Galactic Colors Control Server/Commands/OpenCommand.cs deleted file mode 100644 index 3eee375..0000000 --- a/Galactic Colors Control Server/Commands/OpenCommand.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Net.Sockets; - -namespace Galactic_Colors_Control_Server.Commands -{ - public class OpenCommand : ICommand - { - public string Name { get { return "open"; } } - public string DescText { get { return "Opens server for connections."; } } - public string HelpText { get { return "Use /open to restart connection process"; } } - public bool IsServer { get { return true; } } - public bool IsClient { get { return false; } } - public bool IsClientSide { get { return false; } } - public bool IsNoConnect { get { return false; } } - public int minArgs { get { return 0; } } - public int maxArgs { get { return 0; } } - - public void Execute(string[] args, Socket soc, bool server = false) - { - if (!Program._open) - { - Program._open = true; - Logger.Write("Server opened", Logger.logType.warm); - } - else - { - Utilities.ConsoleWrite("Server already open"); - } - } - } -} diff --git a/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs new file mode 100644 index 0000000..4077030 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs @@ -0,0 +1,36 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyClientCommand : ICommand + { + public string Name { get { return "client"; } } + public string DescText { get { return "Lists party clients."; } } + public string HelpText { get { return "Use 'party client' to show party clients list."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + int partyId = -1; + if (!Utilities.AccessParty(ref partyId, args, false, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + string[] data = new string[Program.parties[partyId].clients.Count]; + int i = 0; + foreach (Socket client in Program.parties[partyId].clients) + { + data[i] = Utilities.GetName(client); + i++; + } + return new RequestResult(ResultTypes.OK, data); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs new file mode 100644 index 0000000..a0f71c5 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs @@ -0,0 +1,33 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyCloseCommand : ICommand + { + public string Name { get { return "close"; } } + public string DescText { get { return "Closes party."; } } + public string HelpText { get { return "Use 'party close' to close party for join."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + int partyId = -1; + if (!Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (!Program.parties[partyId].open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program.parties[partyId].open = false; + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs new file mode 100644 index 0000000..d117eb1 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs @@ -0,0 +1,51 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyCreateCommand : ICommand + { + public string Name { get { return "create"; } } + public string DescText { get { return "Create new party."; } } + public string HelpText { get { return "Use 'party create [name] [size]' to create new party."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 2; } } + public int maxArgs { get { return 2; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if (!server && Program.clients[soc].partyID != -1) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + int size; + if (!int.TryParse(args[3], out size)) + return new RequestResult(ResultTypes.Error, Common.Strings("Format")); + + if (size < 1) + return new RequestResult(ResultTypes.Error, Common.Strings("TooSmall")); + + if (size > Program.config.size) + return new RequestResult(ResultTypes.Error, Common.Strings("TooBig")); + + if (Program.parties.Count >= Program.config.partysize) + return new RequestResult(ResultTypes.Error, Common.Strings("Full")); + + Program.AddParty(new Party(args[2], size, Utilities.GetName(soc))); + Program.logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.GetPartyID(false), Logger.logType.info); + if (server) + { + Program.selectedParty = Program.GetPartyID(false); + } + else + { + Program.clients[soc].partyID = Program.GetPartyID(false); + } + return new RequestResult(ResultTypes.OK, new string[3] { args[2], size.ToString(), (Program.GetPartyID(false)).ToString() }); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs new file mode 100644 index 0000000..77c6b77 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs @@ -0,0 +1,61 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyJoinCommand : ICommand + { + public string Name { get { return "join"; } } + public string DescText { get { return "Join a party."; } } + public string HelpText { get { return "Use 'party join [id] ' to join a party."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 1; } } + public int maxArgs { get { return 2; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if ((server && Program.selectedParty != -1) || (!server && Program.clients[soc].partyID != -1)) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + int id; + if (!int.TryParse(args[2], out id)) + return new RequestResult(ResultTypes.Error, Common.Strings("Format")); + + if (!Program.parties.ContainsKey(id)) + return new RequestResult(ResultTypes.Error, Common.Strings("CantFind")); + + Party party = Program.parties[id]; + if (args.Length == 3) + { + Array.Resize(ref args, 4); + args[3] = ""; + } + if (!server && !party.TestPassword(args[3])) + return new RequestResult(ResultTypes.Error, Common.Strings("Password")); + + if (server) + { + Program.selectedParty = id; + return new RequestResult(ResultTypes.OK); + } + else + { + if (!party.open) + return new RequestResult(ResultTypes.Error, Common.Strings("Close")); + + if (party.clients.Count + 1 > party.size) + return new RequestResult(ResultTypes.Error, Common.Strings("Full")); + + Program.clients[soc].partyID = id; + Utilities.BroadcastParty(new EventData(EventTypes.PartyJoin, Common.Strings(Utilities.GetName(soc))), id); + return new RequestResult(ResultTypes.OK); + } + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs new file mode 100644 index 0000000..71e88f3 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs @@ -0,0 +1,38 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyKickCommand : ICommand + { + public string Name { get { return "kick"; } } + public string DescText { get { return "Kick player from party."; } } + public string HelpText { get { return "Use 'party kick [name] ' to kick palyer from party"; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 1; } } + public int maxArgs { get { return 2; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + int partyId = -1; + if (!Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + Socket target = null; + foreach (Socket client in Program.parties[partyId].clients) + { + if (Utilities.GetName(client) == args[2]) { target = client; } + } + if (target == null) + return new RequestResult(ResultTypes.Error, Common.Strings("CantFind")); + + Utilities.Send(target, new EventData(EventTypes.PartyKick, args.Length > 3 ? Common.Strings(args[2]) : null)); + return Manager.Execute(new string[2] { "party", "leave" }, target, false); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs new file mode 100644 index 0000000..d23b4c5 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs @@ -0,0 +1,42 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyLeaveCommand : ICommand + { + public string Name { get { return "leave"; } } + public string DescText { get { return "Leave party."; } } + public string HelpText { get { return "Use 'party leave' to leave current party"; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if (server) + { + Program.selectedParty = -1; + return new RequestResult(ResultTypes.OK); + } + else + { + int partyId = -1; + if (!Utilities.AccessParty(ref partyId, args, false, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (Program.parties[partyId].IsOwner(Utilities.GetName(soc))) + return new RequestResult(ResultTypes.Error, Common.Strings("Owner")); + + Program.clients[soc].partyID = -1; + Utilities.BroadcastParty(new EventData(EventTypes.PartyLeave, Common.Strings(Utilities.GetName(soc))), partyId); + return new RequestResult(ResultTypes.OK); + } + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs new file mode 100644 index 0000000..65063ae --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs @@ -0,0 +1,37 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyListCommand : ICommand + { + public string Name { get { return "list"; } } + public string DescText { get { return "Shows parties list."; } } + public string HelpText { get { return "Use 'party list' to show parties list."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if (Program.parties.Keys.Count == 0) + return new RequestResult(ResultTypes.Error, Common.Strings("AnyParty")); + + string[] text = new string[Program.parties.Keys.Count]; + int i = 0; + foreach (int key in Program.parties.Keys) + { + Party party = Program.parties[key]; + text[i] = (key + " : " + party.name + " : " + party.count + "/" + party.size + " : " + (party.open ? (party.isPrivate ? "private" : "open") : "close")); + i++; + } + return new RequestResult(ResultTypes.OK, text); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs new file mode 100644 index 0000000..271772e --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs @@ -0,0 +1,33 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyOpenCommand : ICommand + { + public string Name { get { return "open"; } } + public string DescText { get { return "Opens party."; } } + public string HelpText { get { return "Use 'party open' to open party for join."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + int partyId = -1; + if (!Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (Program.parties[partyId].open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program.parties[partyId].open = true; + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs new file mode 100644 index 0000000..fffb0ef --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs @@ -0,0 +1,39 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyPasswordCommand : ICommand + { + public string Name { get { return "password"; } } + public string DescText { get { return "Set party password."; } } + public string HelpText { get { return "Use 'party password [newPass] ' to set party private with password."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 1; } } + public int maxArgs { get { return 2; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + int partyId = -1; + if (!Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (args.Length == 3) + { + Array.Resize(ref args, 4); + args[3] = ""; + } + + if (!Program.parties[partyId].SetPassword(args[2], args[3])) + return new RequestResult(ResultTypes.Error, Common.Strings("Password")); + + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs new file mode 100644 index 0000000..cde3708 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs @@ -0,0 +1,42 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyStatusCommand : ICommand + { + public string Name { get { return "status"; } } + public string DescText { get { return "Shows party status."; } } + public string HelpText { get { return "Use 'party status' to show party status."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + int partyId = -1; + if (!Utilities.AccessParty(ref partyId, args, false, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + Party party = Program.parties[partyId]; + if (server) + { + string text = ""; + text += ("Name: " + party.name + Environment.NewLine); + text += ("Count: " + party.count + "/" + party.size + Environment.NewLine); + text += ("Status: " + (party.isPrivate ? "private" : (party.open ? "open" : "close"))); + return new RequestResult(ResultTypes.OK, Common.Strings(text)); + } + else + { + return new RequestResult(ResultTypes.OK, new string[4] { party.name, party.count.ToString(), party.size.ToString(), (party.isPrivate ? "private" : (party.open ? "open" : "close")) }); + } + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs new file mode 100644 index 0000000..8fb03e0 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs @@ -0,0 +1,36 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class PartyStopCommand : ICommand + { + public string Name { get { return "stop"; } } + public string DescText { get { return "Stop party."; } } + public string HelpText { get { return "Use 'party stop' to stop current party"; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + int partyId = -1; + if (!Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + foreach (Socket client in Program.parties[partyId].clients) + { + Manager.Execute(new string[4] { "party", "kick", Utilities.GetName(client), "stop_party" }, soc, server); + } + Program.logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info, server ? Logger.logConsole.show : Logger.logConsole.normal); + if (Program.selectedParty == partyId) { Program.selectedParty = -1; } + Program.parties.Remove(partyId); + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/PingCommand.cs b/Galactic Colors Control Server/Commands/PingCommand.cs index 3938c37..80746f0 100644 --- a/Galactic Colors Control Server/Commands/PingCommand.cs +++ b/Galactic Colors Control Server/Commands/PingCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,8 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "ping"; } } public string DescText { get { return "Clears the console screen."; } } - public string HelpText { get { return "Use /ping to display our ping."; } } + public string HelpText { get { return "Use 'ping' to display our ping."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return false; } } public bool IsClient { get { return true; } } public bool IsClientSide { get { return true; } } @@ -14,9 +17,9 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - + return new RequestResult(ResultTypes.Error, Common.Strings("ClientSide")); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/SayCommand.cs b/Galactic Colors Control Server/Commands/SayCommand.cs new file mode 100644 index 0000000..ef519c0 --- /dev/null +++ b/Galactic Colors Control Server/Commands/SayCommand.cs @@ -0,0 +1,34 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class SayCommand : ICommand + { + public string Name { get { return "say"; } } + public string DescText { get { return "Said something."; } } + public string HelpText { get { return "Use 'say [text]' to said something."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 1; } } + public int maxArgs { get { return 1; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if (args[1].Length == 0) + return new RequestResult(ResultTypes.Error, Common.Strings("AnyMessage")); + + if (!Utilities.IsConnect(soc)) + return new RequestResult(ResultTypes.Error, Common.Strings("MustBeConnected")); + + int party = -1; + party = Utilities.GetParty(soc); + Utilities.BroadcastParty(new EventData(EventTypes.ChatMessage, Common.Strings(Utilities.GetName(soc) + " : " + args[1])), party); + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs new file mode 100644 index 0000000..a9a44bc --- /dev/null +++ b/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs @@ -0,0 +1,30 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class ServerCloseCommand : ICommand + { + public string Name { get { return "close"; } } + public string DescText { get { return "Close server."; } } + public string HelpText { get { return "Use 'server close' to close server for connections"; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return false; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if (!Program._open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program._open = false; + Program.logger.Write("Server closed", Logger.logType.warm, Logger.logConsole.show); + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs new file mode 100644 index 0000000..6ea0a12 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs @@ -0,0 +1,30 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class ServerOpenCommand : ICommand + { + public string Name { get { return "open"; } } + public string DescText { get { return "Open server."; } } + public string HelpText { get { return "Use 'server open' to open server for connections"; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return false; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if (Program._open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program._open = true; + Program.logger.Write("Server opened", Logger.logType.warm, Logger.logConsole.show); + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs new file mode 100644 index 0000000..947a515 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs @@ -0,0 +1,29 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class ServerStatusCommand : ICommand + { + public string Name { get { return "status"; } } + public string DescText { get { return "Shows server status."; } } + public string HelpText { get { return "Use 'server status' to display server actual status."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return false; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + string text = ""; + text += "Server : " + (Program._open ? "open" : "close"); + text += "Clients : " + Program.clients.Count + "/" + Program.config.size; + text += "Parties : " + Program.parties.Count; + return new RequestResult(ResultTypes.OK, Common.Strings(text)); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs new file mode 100644 index 0000000..02ef516 --- /dev/null +++ b/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs @@ -0,0 +1,25 @@ +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class ServerStopCommand : ICommand + { + public string Name { get { return "stop"; } } + public string DescText { get { return "Stop the server."; } } + public string HelpText { get { return "Use 'server stop' to completly stop server."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return false; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 0; } } + public int maxArgs { get { return 0; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + Program._run = false; + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/StatusCommand.cs b/Galactic Colors Control Server/Commands/StatusCommand.cs deleted file mode 100644 index 57fcd7a..0000000 --- a/Galactic Colors Control Server/Commands/StatusCommand.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Net.Sockets; - -namespace Galactic_Colors_Control_Server.Commands -{ - public class StatusCommand : ICommand - { - public string Name { get { return "status"; } } - public string DescText { get { return "Shows server status."; } } - public string HelpText { get { return "Use /status to display server actual status."; } } - public bool IsServer { get { return true; } } - public bool IsClient { get { return false; } } - public bool IsClientSide { get { return false; } } - public bool IsNoConnect { get { return false; } } - public int minArgs { get { return 0; } } - public int maxArgs { get { return 0; } } - - public void Execute(string[] args, Socket soc, bool server = false) - { - if (Program._open) - { - Utilities.ConsoleWrite("Server open"); - } - else { - Utilities.ConsoleWrite("Server close"); - } - } - } -} diff --git a/Galactic Colors Control Server/Commands/TimeCommand.cs b/Galactic Colors Control Server/Commands/TimeCommand.cs index 98d3a00..4a34ab2 100644 --- a/Galactic Colors Control Server/Commands/TimeCommand.cs +++ b/Galactic Colors Control Server/Commands/TimeCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,8 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "time"; } } public string DescText { get { return "Gives server time."; } } - public string HelpText { get { return "Use /time to display server time. (format is server dependent)"; } } + public string HelpText { get { return "Use 'time' to display server time."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } public bool IsClientSide { get { return false; } } @@ -15,9 +18,9 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - Utilities.Return(DateTime.Now.ToLongTimeString(), soc, server); + return new RequestResult(ResultTypes.OK, Common.Strings(DateTime.Now.ToLongTimeString())); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Config.cs b/Galactic Colors Control Server/Config.cs index af16ae7..57b48ba 100644 --- a/Galactic Colors Control Server/Config.cs +++ b/Galactic Colors Control Server/Config.cs @@ -1,14 +1,12 @@ -using System; -using System.Collections.Generic; +using Galactic_Colors_Control_Common; +using System; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace Galactic_Colors_Control_Server { + //TODO Common config [XmlRoot("config")] public class Config { @@ -16,8 +14,10 @@ namespace Galactic_Colors_Control_Server public Logger.logType logLevel = Logger.logType.info; public int port = 25001; public int size = 20; - public ConsoleColor[] logForeColor = new ConsoleColor[5] {ConsoleColor.Gray , ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White}; - public ConsoleColor[] logBackColor = new ConsoleColor[5] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; + public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White }; + public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; + public int lang = 1; + public int partysize = 10; /// /// Load config from xml file @@ -26,7 +26,7 @@ namespace Galactic_Colors_Control_Server /// Loaded config public Config Load() { - Logger.Write("Loading config", Logger.logType.info); + Program.logger.Write("Loading config", Logger.logType.info); Config config = new Config(); if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) { @@ -40,17 +40,19 @@ namespace Galactic_Colors_Control_Server } else { - Logger.Write("Old config in Config.xml.old", Logger.logType.warm); + Program.logger.Write("Old config in Config.xml.old", Logger.logType.warm); + File.Delete(AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); config.Save(); } } else { - Logger.Write("Any config file", Logger.logType.error); + Program.logger.Write("Any config file", Logger.logType.error); config.Save(); } if (Program._debug) { config.logLevel = Logger.logType.debug; } + if (Program._dev) { config.logLevel = Logger.logType.dev; } return config; } @@ -60,12 +62,13 @@ namespace Galactic_Colors_Control_Server public void Save() { XmlSerializer xs = new XmlSerializer(typeof(Config)); - if (Program._debug) { logLevel = Logger.logType.info; } + if (Program._debug || Program._dev) { logLevel = Logger.logType.info; } using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) { - xs.Serialize(st,this); + xs.Serialize(st, this); }; if (Program._debug) { logLevel = Logger.logType.debug; } + if (Program._dev) { logLevel = Logger.logType.dev; } } /// @@ -86,7 +89,7 @@ namespace Galactic_Colors_Control_Server catch (XmlException e) { isCorrect = false; - Logger.Write("Error: " + e.Message, Logger.logType.error); + Program.logger.Write("Error: " + e.Message, Logger.logType.error); } } @@ -100,18 +103,18 @@ namespace Galactic_Colors_Control_Server d.Validate((o, e) => { - Logger.Write("Error: " + e.Message, Logger.logType.error); + Program.logger.Write("Error: " + e.Message, Logger.logType.error); isCorrect = false; }); } catch (XmlException e) { isCorrect = false; - Logger.Write("Error: " + e.Message, Logger.logType.error); + Program.logger.Write("Error: " + e.Message, Logger.logType.error); } } return isCorrect; } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/ConfigSchema.xsd b/Galactic Colors Control Server/ConfigSchema.xsd index 7e1457f..1b8f7cb 100644 --- a/Galactic Colors Control Server/ConfigSchema.xsd +++ b/Galactic Colors Control Server/ConfigSchema.xsd @@ -21,7 +21,9 @@ + + - + \ No newline at end of file diff --git a/Galactic Colors Control Server/Data.cs b/Galactic Colors Control Server/Data.cs deleted file mode 100644 index 587c7a5..0000000 --- a/Galactic Colors Control Server/Data.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Net.Sockets; - -namespace Galactic_Colors_Control_Server -{ - public class Data - { - public int id; - public int status = -1; - public string pseudo = ""; - } -} diff --git a/Galactic Colors Control Server/Galactic Colors Control Server.csproj b/Galactic Colors Control Server/Galactic Colors Control Server.csproj index 3845bbe..648b04e 100644 --- a/Galactic Colors Control Server/Galactic Colors Control Server.csproj +++ b/Galactic Colors Control Server/Galactic Colors Control Server.csproj @@ -53,24 +53,42 @@ + + Properties\AssemblyInfoCommon.cs + + + + + + + + + + + + + + + + - + - + - - + + - - + + + - - + @@ -94,6 +112,13 @@ false + + + {022a69ce-22b5-4934-be9f-a9c6df9557ed} + Galactic Colors Control Common + + +