diff options
Diffstat (limited to 'source/WindowsFormsApplication1/Online')
6 files changed, 1162 insertions, 0 deletions
diff --git a/source/WindowsFormsApplication1/Online/ConnectionManager.Designer.cs b/source/WindowsFormsApplication1/Online/ConnectionManager.Designer.cs new file mode 100644 index 0000000..89abcca --- /dev/null +++ b/source/WindowsFormsApplication1/Online/ConnectionManager.Designer.cs @@ -0,0 +1,129 @@ +namespace ShiftOS +{ + partial class ConnectionManager + { + /// <summary> + /// Required designer variable. + /// </summary> + private System.ComponentModel.IContainer components = null; + + /// <summary> + /// Clean up any resources being used. + /// </summary> + /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// <summary> + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// </summary> + private void InitializeComponent() + { + this.panel1 = new System.Windows.Forms.Panel(); + this.lbconnections = new System.Windows.Forms.ListBox(); + this.flbuttons = new System.Windows.Forms.FlowLayoutPanel(); + this.btnadd = new System.Windows.Forms.Button(); + this.btnconnect = new System.Windows.Forms.Button(); + this.btndisconnect = new System.Windows.Forms.Button(); + this.panel1.SuspendLayout(); + this.flbuttons.SuspendLayout(); + this.SuspendLayout(); + // + // panel1 + // + this.panel1.Controls.Add(this.flbuttons); + this.panel1.Controls.Add(this.lbconnections); + this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel1.Location = new System.Drawing.Point(0, 0); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(684, 531); + this.panel1.TabIndex = 0; + // + // lbconnections + // + this.lbconnections.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.lbconnections.FormattingEnabled = true; + this.lbconnections.Location = new System.Drawing.Point(13, 13); + this.lbconnections.Name = "lbconnections"; + this.lbconnections.Size = new System.Drawing.Size(659, 472); + this.lbconnections.TabIndex = 0; + this.lbconnections.SelectedIndexChanged += new System.EventHandler(this.lbconnections_SelectedIndexChanged); + // + // flbuttons + // + this.flbuttons.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.flbuttons.Controls.Add(this.btnadd); + this.flbuttons.Controls.Add(this.btnconnect); + this.flbuttons.Controls.Add(this.btndisconnect); + this.flbuttons.Location = new System.Drawing.Point(13, 489); + this.flbuttons.Name = "flbuttons"; + this.flbuttons.Size = new System.Drawing.Size(659, 30); + this.flbuttons.TabIndex = 1; + // + // btnadd + // + this.btnadd.Location = new System.Drawing.Point(3, 3); + this.btnadd.Name = "btnadd"; + this.btnadd.Size = new System.Drawing.Size(75, 23); + this.btnadd.TabIndex = 0; + this.btnadd.Text = "Add"; + this.btnadd.UseVisualStyleBackColor = true; + this.btnadd.Click += new System.EventHandler(this.btnadd_Click); + // + // btnconnect + // + this.btnconnect.Location = new System.Drawing.Point(84, 3); + this.btnconnect.Name = "btnconnect"; + this.btnconnect.Size = new System.Drawing.Size(75, 23); + this.btnconnect.TabIndex = 1; + this.btnconnect.Text = "Connect"; + this.btnconnect.UseVisualStyleBackColor = true; + this.btnconnect.Click += new System.EventHandler(this.btnconnect_Click); + // + // btndisconnect + // + this.btndisconnect.Location = new System.Drawing.Point(165, 3); + this.btndisconnect.Name = "btndisconnect"; + this.btndisconnect.Size = new System.Drawing.Size(75, 23); + this.btndisconnect.TabIndex = 2; + this.btndisconnect.Text = "Disconnect"; + this.btndisconnect.UseVisualStyleBackColor = true; + this.btndisconnect.Click += new System.EventHandler(this.btndisconnect_Click); + // + // ConnectionManager + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(684, 531); + this.Controls.Add(this.panel1); + this.Name = "ConnectionManager"; + this.Text = "ConnectionManager"; + this.Load += new System.EventHandler(this.ConnectionManager_Load); + this.panel1.ResumeLayout(false); + this.flbuttons.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Panel panel1; + private System.Windows.Forms.FlowLayoutPanel flbuttons; + private System.Windows.Forms.Button btnadd; + private System.Windows.Forms.Button btnconnect; + private System.Windows.Forms.Button btndisconnect; + private System.Windows.Forms.ListBox lbconnections; + } +}
\ No newline at end of file diff --git a/source/WindowsFormsApplication1/Online/ConnectionManager.cs b/source/WindowsFormsApplication1/Online/ConnectionManager.cs new file mode 100644 index 0000000..eaf2a24 --- /dev/null +++ b/source/WindowsFormsApplication1/Online/ConnectionManager.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ShiftOS +{ + public partial class ConnectionManager : Form + { + public ConnectionManager() + { + InitializeComponent(); + } + + string selectednet = null; + + private void lbconnections_SelectedIndexChanged(object sender, EventArgs e) + { + try + { + selectednet = lbconnections.SelectedItem.ToString(); + SetupUI(); + } + catch + { + selectednet = null; + SetupUI(); + } + } + + public void SetupUI() + { + if(selectednet != null) + { + btnconnect.Visible = !Package_Grabber.clients[selectednet].IsConnected; + btndisconnect.Visible = Package_Grabber.clients[selectednet].IsConnected; + } + else + { + btnconnect.Hide(); + btndisconnect.Hide(); + } + } + + private void ConnectionManager_Load(object sender, EventArgs e) + { + SetupUI(); + var t = new Timer(); + t.Interval = 500; + t.Tick += (object s, EventArgs a) => + { + lbconnections.Items.Clear(); + foreach(var itm in Package_Grabber.clients) + { + lbconnections.Items.Add(itm.Key); + } + }; + t.Start(); + } + + private void btndisconnect_Click(object sender, EventArgs e) + { + Package_Grabber.Disconnect(selectednet); + SetupUI(); + } + + private void btnconnect_Click(object sender, EventArgs e) + { + Package_Grabber.ConnectToServer(selectednet, 7429); + SetupUI(); + } + + private void btnadd_Click(object sender, EventArgs e) + { + API.CreateInfoboxSession("Add connection", "Please type the IP Address or hostname of the server.", infobox.InfoboxMode.TextEntry); + API.InfoboxSession.FormClosing += (o, a) => + { + var res = API.GetInfoboxResult(); + if(res != "Cancelled") + { + Package_Grabber.ConnectToServer(res, 7429); + } + }; + } + } +} diff --git a/source/WindowsFormsApplication1/Online/ConnectionManager.resx b/source/WindowsFormsApplication1/Online/ConnectionManager.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/source/WindowsFormsApplication1/Online/ConnectionManager.resx @@ -0,0 +1,120 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> +</root>
\ No newline at end of file diff --git a/source/WindowsFormsApplication1/Online/Hacking/Matchmaker.cs b/source/WindowsFormsApplication1/Online/Hacking/Matchmaker.cs new file mode 100644 index 0000000..1fb6f1b --- /dev/null +++ b/source/WindowsFormsApplication1/Online/Hacking/Matchmaker.cs @@ -0,0 +1,383 @@ +/* ShiftOS Online Hacker Battles - Matchmaker + * + * These classes deal with keeping things in line on the client-side of things. + * They deal with CSP (Client-Side Prediction), sending and receiving messages to + * and from the ShiftOS server, as well as making sure that when you join or leave a + * lobby, the server and other clients actually KNOW you did. + * + * I wouldn't mess with this unless you really, really understand what you're doing, + * as in most cases, modification to the server is required as well (in the case of + * adding new commands). I'd leave modification to the system creator (Michael VanOverbeek) who + * actually wrote this. He's the guy who knows all about how the server works. Wait... why am + * I talking in third person? + */ + +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ShiftOS.Online.Hacking +{ + public class Matchmaker + { + //All available lobbies. + public static List<ServerInfo> Servers = null; + + //All players in the lobby. + public static List<Network> Players = null; + + //Some useful info about the lobby in which the player is. + //Also contains server IP to be sent to Package_Grabber.SendMessage(). + public static ServerInfo SelectedServer = null; + + //Enemy network information (name, codepoints, etc) + public static Network SelectedNetwork = null; + + //There's only one transmitter because generally the player + //won't be interacting with the enemy playfield enough to + //warrent a request to the server. + public static NetListener SelectedNetworkListener = null; //Listen for updates from the opponent. + public static NetTransmitter SelectedNetworkTransmitter = null; //Send messages to the server for enemy updates on opponent clients. + public static NetListener PlayerListener = null; //For receiving non-CSP updates from the server. + public static NetTransmitter SecondaryTransmitter = null; //For sending CSP-created update requests to the opponent (enemy health damage, etc) + + //Timer that'll run during matchmaking. + public static Timer MakerTimer = null; + + /// <summary> + /// This either starts matchmaking or grabs server info. Try it out I guess. + /// + /// Fires: Matchmaker.Initiated + /// </summary> + public static void Initiate() + { + MakerTimer = new Timer(); + MakerTimer.Interval = 100; + + Servers = new List<ServerInfo>(); + foreach(var c in Package_Grabber.clients) + { + c.Value.OnReceived += (o, e) => + { + try + { + var om = (e.Data.Object as ObjectModel); + if (om.Command == "server_info") + { + var si = JsonConvert.DeserializeObject<ServerInfo>(om.OptionalObject as string); + si.IPAddress = c.Value.RemoteHost; + Servers.Add(si); + invoke(() => + { + Initiated?.Invoke(null, new EventArgs()); + }); + } + } + catch + { + + } + }; + Package_Grabber.SendMessage(c.Value.RemoteHost, "get_info"); + } + } + + /// <summary> + /// Matchmake in the supplied lobby. + /// + /// Fires: MorePlayersFound upon player leave/join. + /// </summary> + /// <param name="si">The server to matchmake in.</param> + public static void Matchmake(ServerInfo si) + { + SelectedServer = si; + var rnd = new Random(); + Players = new List<Network>(); + var server = Package_Grabber.clients[si.IPAddress]; + server.OnReceived += (o, e) => + { + try + { + var om = e.Data.Object as ObjectModel; + if (om.Command == "matchmaking") + { + Players = JsonConvert.DeserializeObject<List<Network>>(om.OptionalObject as string); + invoke(() => + { + MorePlayersFound?.Invoke(null, new EventArgs()); + }); + } + } + catch + { + + } + }; + Package_Grabber.SendMessage(si.IPAddress, "get_matchmaking"); + int index = 0; + MakerTimer.Tick += (o, e) => + { + try + { + if (Players[index].Name != API.CurrentSave.MyOnlineNetwork.Name && Players[index].Name != null) + { + SelectedNetwork = Players[index]; + MakerTimer.Stop(); + PlayerListener = new NetListener(si, SelectedNetwork); + SecondaryTransmitter = new NetTransmitter(si, API.CurrentSave.MyOnlineNetwork); + SelectedNetworkListener = new NetListener(si, API.CurrentSave.MyOnlineNetwork); + SelectedNetworkTransmitter = new NetTransmitter(si, SelectedNetwork); + var h = new HackUI(SelectedNetworkTransmitter, SelectedNetworkListener, PlayerListener, SecondaryTransmitter); + h.Show(); + Package_Grabber.SendMessage(SelectedServer.IPAddress, $"leave_lobby {JsonConvert.SerializeObject(API.CurrentSave.MyOnlineNetwork)}"); + } + else + { + index += 1; + } + } + catch + { + } + }; + MakerTimer.Interval = 50; + MakerTimer.Start(); + } + + + /// <summary> + /// Fired when Initiate() finishes. + /// </summary> + public static event EventHandler Initiated; + + /// <summary> + /// Fired when someone enters/exits a lobby that we are in. + /// </summary> + public static event EventHandler MorePlayersFound; + + /// <summary> + /// Helper method to allow me to invoke some code on the ShiftOS desktop thread (for UI access) + /// </summary> + /// <param name="method">The code to invoke (use a lambda expression or just pump a void through.)</param> + public static void invoke(Action method) + { + API.CurrentSession.Invoke(method); + } + + internal static void DestroySession() + { + Servers.Clear(); + Players.Clear(); + ClearEvents(); + SelectedNetwork = null; + SelectedNetworkTransmitter = null; + SelectedNetworkListener = null; + PlayerListener = null; + //Good to go, I guess. + } + + public static void ClearEvents() + { + Initiated = null; + MorePlayersFound = null; + } + } + + public class NetListener + { + public NetListener(ServerInfo si, Network net) + { + register_events(si, net); + + } + + public List<Module> MyModules = null; + + private void register_events(ServerInfo si, Network net) + { + MyModules = new List<Module>(); + var server = Package_Grabber.clients[si.IPAddress]; + server.OnReceived += (o, e) => + { + if (e.Data.Object is ObjectModel) + { + + var data = (e.Data.Object as ObjectModel); + if (data.Command != null) + { + string[] args = data.Command.Split(' '); + if ((data.OptionalObject as Network)?.Name == net.Name) + { + switch (args[0].ToLower()) + { + case "set_health": + string hn = args[1]; + int hp = Convert.ToInt32(args[2]); + invoke(() => { ModuleHealthSet?.Invoke(this, new Events.Health { host_name = hn, health = hp }); }); + break; + case "place_module": + string hostname = args[1]; + int grade = Convert.ToInt32(args[2]); + int newhp = Convert.ToInt32(args[3]); + int x = Convert.ToInt32(args[4]); + int y = Convert.ToInt32(args[5]); + int type = Convert.ToInt32(args[6]); + var moduleToPlace = new Module { Grade = grade, Hostname = hostname, HP = newhp, Type = type, X = x, Y = y }; + MyModules.Add(moduleToPlace); + invoke(() => { ModulePlaced?.Invoke(this, new Events.ModulePlaced { new_module = moduleToPlace }); }); + break; + case "remove_module": + string hostnametoremove = args[1]; + var m = new Module(); + foreach (var mod in MyModules) + { + if (mod.Hostname == hostnametoremove) + { + m = mod; + } + } + MyModules.Remove(m); + + invoke(() => { ModuleRemoved?.Invoke(this, new Events.ModuleRemoved { new_module = hostnametoremove }); }); + break; + case "upgrade": + invoke(() => + { + string hostnametoupgrade = args[1]; + int newgrade = Convert.ToInt32(args[2]); + ModuleUpgraded?.Invoke(this, new Events.ModuleUpgraded { hostname = hostnametoupgrade, grade = newgrade }); + }); + break; + case "finish": + string json = data.Command.Remove(0, 7); + var winner = JsonConvert.DeserializeObject<Network>(json); + Won?.Invoke(this, new Events.Won(winner)); + break; + case "disable": + invoke(() => + { + string name = args[1]; + ModuleDisabled?.Invoke(this, new Events.Disabled { hostName = name }); + }); + break; + } + } + } + } + }; + } + + public void invoke(Action method) + { + API.CurrentSession.Invoke(method); + } + + public event EventHandler<Events.Health> ModuleHealthSet; + public event EventHandler<Events.ModulePlaced> ModulePlaced; + public event EventHandler<Events.ModuleRemoved> ModuleRemoved; + public event EventHandler<Events.ModuleUpgraded> ModuleUpgraded; + public event EventHandler<Events.Disabled> ModuleDisabled; + public event EventHandler<Events.Won> Won; + } + + public class NetTransmitter + { + public ServerInfo serverInfo = null; + public Network EnemyIdent = null; + + public NetTransmitter(ServerInfo si, Network enemy) + { + EnemyIdent = enemy; + serverInfo = si; + //HackUI will handle everything else to do with our network. + } + + public void send_message(Messages msg, object value) + { + switch(msg) + { + case Messages.PlaceModule: + var m = value as Module; + Package_Grabber.SendMessage(serverInfo.IPAddress, $"place_module {m.Hostname} {m.Grade} {m.HP} {m.X} {m.Y} {m.Type}", EnemyIdent); + break; + case Messages.Upgrade: + string upgradestr = value as string; + Package_Grabber.SendMessage(serverInfo.IPAddress, $"upgrade {upgradestr}", EnemyIdent); + break; + case Messages.RemoveModule: + string hostnametoremove = value as string; + Package_Grabber.SendMessage(serverInfo.IPAddress, $"remove_module {hostnametoremove}", EnemyIdent); + break; + case Messages.SetHealth: + string healthsetstr = value as string; + Package_Grabber.SendMessage(serverInfo.IPAddress, $"set_health {healthsetstr}", EnemyIdent); + break; + case Messages.FinishBattle: + string json = JsonConvert.SerializeObject(value as Network); + Package_Grabber.SendMessage(serverInfo.IPAddress, $"finish {json}"); + break; + case Messages.Disabled: + string hnamestr = value as string; + Package_Grabber.SendMessage(serverInfo.IPAddress, $"disable {hnamestr}", EnemyIdent); + break; + } + } + + public enum Messages + { + PlaceModule, + Upgrade, + RemoveModule, + SetHealth, + Disabled, + FinishBattle, + } + } + + namespace Events + { + public class Health : EventArgs + { + public string host_name { get; set; } + public int health { get; set; } + } + + public class Disabled : EventArgs + { + public string hostName { get; set; } + } + + public class Won : EventArgs + { + public Network Winner { get; private set; } + + public Won(Network winner) + { + Winner = winner; + } + } + + public class ModulePlaced : EventArgs + { + public Module new_module { get; set; } + } + + public class ModuleRemoved : EventArgs + { + public string new_module { get; set; } + } + + public class ModuleUpgraded : EventArgs + { + public string hostname { get; set; } + public int grade { get; set; } + } + + + + } +} diff --git a/source/WindowsFormsApplication1/Online/Hacking/Objects.cs b/source/WindowsFormsApplication1/Online/Hacking/Objects.cs new file mode 100644 index 0000000..5012fcc --- /dev/null +++ b/source/WindowsFormsApplication1/Online/Hacking/Objects.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ShiftOS.Online.Hacking +{ + [Serializable] + public class Module + { + public string Hostname { get; set; } + public int Grade { get; set; } + public int HP { get; set; } + public int X { get; set; } + public int Y { get; set; } + public int Type { get; set; } //will be converted by the client + } + + [Serializable] + public class Network + { + public string Name { get; set; } + public int Codepoints { get; set; } + public string Description { get; set; } + public int Losses { get; set; } + public int Wins { get; set; } + } + + [Serializable] + public class ServerInfo + { + public string ServerName { get; set; } + public int PlayersAwaitingMatch { get; set; } + public string IPAddress { get; set; } + } +} diff --git a/source/WindowsFormsApplication1/Online/Package_Grabber.cs b/source/WindowsFormsApplication1/Online/Package_Grabber.cs new file mode 100644 index 0000000..b6bbc61 --- /dev/null +++ b/source/WindowsFormsApplication1/Online/Package_Grabber.cs @@ -0,0 +1,402 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using System.IO; +using System.IO.Compression; +using Newtonsoft.Json; +using System.Windows.Forms; +using System.Threading; +using System.Drawing; +using NetSockets; + +namespace ShiftOS +{ + [Serializable] + public class ObjectModel + { + public string SysId { get; set; } + public string Command { get; set; } + public object OptionalObject { get; set; } + } + + [Serializable] + public class ChatUser + { + public string Name { get; set; } + public event EventHandler OnJoin; + public event EventHandler OnLeave; + } + + [Serializable] + public class ChatMessage + { + public string Text { get; set; } + public ChatUser User { get; set; } + } + + class Package_Grabber + { + + + public static Dictionary<string, NetObjectClient> clients = null; + + /// <summary> + /// Connect to a ShiftOS server + /// </summary> + /// <param name="address">IP address</param> + /// <param name="port">Port (typically this is 4433.)</param> + public static void ConnectToServer(string address, int port) + { + if(clients == null) + { + clients = new Dictionary<string, NetObjectClient>(); + } + bool blacklisted = false; + string blacklist = new WebClient().DownloadString("http://playshiftos.ml/server/blacklist"); + string[] splitter = blacklist.Split(';'); + foreach (string addr in splitter) + { + try + { + string[] addSplitter = addr.Split(':'); + string host = addSplitter[0]; + int prt = Convert.ToInt32(addSplitter[1]); + if(address == host && port == prt) + { + blacklisted = true; + } + } + catch + { + + } + } + if (!blacklisted) + { + var client = new NetObjectClient(); + client.OnReceived += (object s, NetReceivedEventArgs<NetObject> a) => + { + try + { + var obj = (ObjectModel)a.Data.Object; + if (obj.Command == "set_ident") + { + this_id = obj.SysId; + } + } + catch + { + + } + }; + + try + { + client.Connect(address, port); + clients.Add(client.RemoteHost, client); + } + catch + { + } + } + else + { + API.CreateInfoboxSession("Server Connection Error", "The server you are trying to connect to has been blacklisted for breaking the rules of the Server Showcase, therefore you may not connect to it.", infobox.InfoboxMode.Info); + } + } + + private static string this_id = ""; + + /// <summary> + /// Send a message to a server. + /// </summary> + /// <param name="host">Server hostname/IP</param> + /// <param name="text">Messge contents.</param> + public static void SendMessage(string host, string text) + { + var obj = new ObjectModel(); + obj.SysId = this_id; + obj.Command = text; + try { + clients[host].Send(new NetObject("test", obj)); + } + catch + { + + } + } + + /// <summary> + /// Send a message to a server containing a .NET object. + /// </summary> + /// <param name="host">Server hostname/IP</param> + /// <param name="text">Message text.</param> + /// <param name="optional">The object to go with it.</param> + public static void SendMessage(string host, string text, object optional) + { + var obj = new ObjectModel(); + obj.SysId = this_id; + obj.Command = text; + obj.OptionalObject = optional; + try { + clients[host].Send(obj.SysId, obj); + } + catch + { + + } + } + + + + /// <summary> + /// Disconnect from a server. + /// </summary> + /// <param name="host">Server host.</param> + public static void Disconnect(string host) + { + if(clients.ContainsKey(host)) + { + if(clients[host].IsConnected == true) + { + clients[host].Disconnect(); + } + } + } + + + /// <summary> + /// Download a package through spkg. + /// </summary> + /// <param name="pkgname">Package name</param> + /// <returns>Could it download?</returns> + public static bool GetPackage(string pkgname) + { + bool result = true; + try + { + string downloadpath = Paths.Mod_Temp; + if (!Directory.Exists(downloadpath)) + { + Directory.CreateDirectory(downloadpath); + } else + { + Directory.Delete(downloadpath, true); + Directory.CreateDirectory(downloadpath); + } + WebClient wc = new WebClient(); + wc.DownloadFile("http://playshiftos.ml/shiftnet/packages/" + pkgname + ".pkg", downloadpath + pkgname + ".pkg"); + LastPackage_DownloadPath = downloadpath + pkgname + ".pkg"; + } + catch + { + result = false; + } + return result; + } + + public static string LastPackage_DownloadPath = null; + + /// <summary> + /// Extracts the last downloaded package. + /// </summary> + /// <returns>The temp path</returns> + public static string ExtractPackage() + { + if (LastPackage_DownloadPath != null) + { + string packagedir = null; + if (LastPackage_DownloadPath.EndsWith(".pkg")) + { + packagedir = LastPackage_DownloadPath.Replace(".pkg", ""); + } + else + { + packagedir = LastPackage_DownloadPath.Replace(".stp", ""); + } + if (Directory.Exists(packagedir)) + { + Directory.Delete(packagedir, true); + } + ZipFile.ExtractToDirectory(LastPackage_DownloadPath, packagedir); + return packagedir; + } + else + { + return "fail"; + } + } + + /// <summary> + /// Extract a specified .stp or .pkg file. + /// </summary> + /// <param name="localpath">File to extract</param> + /// <returns>The new temp path</returns> + public static string ExtractPackage(string localpath) + { + try { + + string packagedir = Paths.Mod_Temp + "pkg"; + if (Directory.Exists(packagedir)) + { + Directory.Delete(packagedir, true); + } + Directory.CreateDirectory(packagedir); + ZipFile.ExtractToDirectory(localpath, packagedir); + return packagedir; + } + catch + { + return "fail"; + } + } + + /// <summary> + /// Install a package from a directory + /// </summary> + /// <param name="dir">The package directory</param> + /// <returns>Could it install?</returns> + public static string InstallPackage(string dir) + { + try + { + string dirsepchar = "\\"; + switch (OSInfo.GetPlatformID()) + { + case "microsoft": + dirsepchar = "\\"; + break; + default: + dirsepchar = "/"; + break; + } + string alfile = null; + foreach (string file in Directory.GetFiles(dir)) + { + if (file.Contains("applauncher")) + { + alfile = file; + } + } + string json = File.ReadAllText(alfile); + if (!Directory.Exists(Paths.Mod_AppLauncherEntries)) + { + Directory.CreateDirectory(Paths.Mod_AppLauncherEntries); + } + ModApplauncherItem itm = JsonConvert.DeserializeObject<ModApplauncherItem>(json); + File.WriteAllText(Paths.Mod_AppLauncherEntries + itm.Name, json); + //Applauncher Entry installed! + if (!Directory.Exists(Paths.Applications + itm.AppDirectory)) + { + Directory.CreateDirectory(Paths.Applications + itm.AppDirectory); + } + + Thread.Sleep(200); + if (!File.Exists(Paths.Applications + itm.AppDirectory + dirsepchar + "Icon.bmp")) + { + File.Copy(dir + "Icon.bmp", Paths.Applications + itm.AppDirectory + dirsepchar + "Icon.bmp"); + } + if (File.Exists(Paths.Applications + itm.AppDirectory + dirsepchar + "app.saa")) + { + File.Delete(Paths.Applications + itm.AppDirectory + dirsepchar + "app.saa"); + } + File.Move(dir + "app.saa", Paths.Applications + itm.AppDirectory + dirsepchar + "app.saa"); + //App installed. + foreach (string file in Directory.GetFiles(dir)) + { + if (file.EndsWith(".dll")) + { + if (!File.Exists(Paths.Applications + itm.AppDirectory + dirsepchar + new FileInfo(file).Name)) + { + //Dependencies are fucking bitches. + File.Copy(file, Paths.Applications + itm.AppDirectory + dirsepchar + new FileInfo(file).Name); + } + } + } + //Dependencies installed. + API.CurrentSession.SetupAppLauncher(); + return "success"; + } + catch (Exception ex) + { + return ex.Message; + } + } + } + + class FTP_API + { + /// <summary> + /// Gets a package image from the ShiftOS website + /// </summary> + /// <param name="ftpFilePath">Image path relative to the packages directory</param> + /// <returns>The image</returns> + [Obsolete] + public static Image GetImage(string ftpFilePath) + { + var request = WebRequest.Create("http://playshiftos.ml/appscape/packages/" + ftpFilePath); + + using (var response = request.GetResponse()) + { + using (var str = response.GetResponseStream()) + { + return Image.FromStream(str); + } + } + } + + [Obsolete] + public static Image GetSkinImage(string ftpFilePath) + { + var request = WebRequest.Create("http://playshiftos.ml/appscape/skins/" + ftpFilePath); + + using (var response = request.GetResponse()) + { + using (var str = response.GetResponseStream()) + { + return Image.FromStream(str); + } + } + } + } + + + [Serializable] + public class AppscapeModder + { + public string DevKey { get; set; } + public string Name { get; set; } + public string Bio { get; set; } + public string BitnoteAddress { get; set; } + } + + [Serializable] + public class AppscapePackage + { + public string Name { get; set; } + public string Address { get; set; } + public string DevKey { get; set; } + public string Description { get; set; } + public string SetupFile { get; set; } + public string PkgIconPath { get; set; } + public string ScreenshotPath { get; set; } + public decimal Cost { get; set; } + public string Server { get; set; } + } + + [Serializable] + public class SkinData + { + public string Name { get; set; } + public string Author { get; set; } + public string Description { get; set; } + public string Download { get; set; } + public string Icon { get; set; } + public string Screenshot { get; set; } + public decimal Cost { get; set; } + public string Server { get; set; } + } +} |
