Skip to content

Instantly share code, notes, and snippets.

@AHartTN
Created July 14, 2011 03:32
Show Gist options
  • Save AHartTN/1081894 to your computer and use it in GitHub Desktop.
Save AHartTN/1081894 to your computer and use it in GitHub Desktop.
Lacuna Expanse
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Text;
using System.Collections;
using LELibrary.Logic;
using LELibrary.Objects;
using System.Collections.ObjectModel;
using System.Dynamic;
namespace LELibrary
{
namespace Logic
{
sealed class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }
}
private sealed class DynamicJsonObject : DynamicObject
{
private readonly IDictionary<string, object> _dictionary;
public DynamicJsonObject(IDictionary<string, object> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
_dictionary = dictionary;
}
public override string ToString()
{
var sb = new StringBuilder("{");
ToString(sb);
return sb.ToString();
}
private void ToString(StringBuilder sb)
{
var firstInDictionary = true;
foreach (var pair in _dictionary)
{
if (!firstInDictionary)
sb.Append(",");
firstInDictionary = false;
var value = pair.Value;
var name = pair.Key;
if (value is string)
{
sb.AppendFormat("{0}:\"{1}\"", name, value);
}
else if (value is IDictionary<string, object>)
{
new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);
}
else if (value is ArrayList)
{
sb.Append(name + ":[");
var firstInArray = true;
foreach (var arrayValue in (ArrayList)value)
{
if (!firstInArray)
sb.Append(",");
firstInArray = false;
if (arrayValue is IDictionary<string, object>)
new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
else if (arrayValue is string)
sb.AppendFormat("\"{0}\"", arrayValue);
else
sb.AppendFormat("{0}", arrayValue);
}
sb.Append("]");
}
else
{
sb.AppendFormat("{0}:{1}", name, value);
}
}
sb.Append("}");
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!_dictionary.TryGetValue(binder.Name, out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}
var dictionary = result as IDictionary<string, object>;
if (dictionary != null)
{
result = new DynamicJsonObject(dictionary);
return true;
}
var arrayList = result as ArrayList;
if (arrayList != null && arrayList.Count > 0)
{
if (arrayList[0] is IDictionary<string, object>)
result = new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x)));
else
result = new List<object>(arrayList.Cast<object>());
}
return true;
}
}
}
public class LeError
{
public int Id { get; set; }
public int Code { get; set; }
public string Message { get; set; }
public string Data { get; set; }
}
public class LeErrors
{
public List<LeError> List { get; set; }
public LeErrors()
{
List = new List<LeError>();
}
}
public class Traffic
{
public LeErrors Errors { get; set; }
public string CompileJsonString(object obj)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(obj).Replace("parms", "params");
}
public dynamic JsonGet(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json-rpc; charset=utf-8";
request.Accept = "application/json-rpc, text/javascript, */*";
request.Method = "GET";
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
string json = "";
if (stream != null)
using (StreamReader sr = new StreamReader(stream))
{
while (!sr.EndOfStream)
{
json += sr.ReadLine();
}
}
return JsonDeserialize(json);
}
public dynamic JsonPost(string url, string strJson, out dynamic result)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json, text/javascript, */*";
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(strJson);
request.ContentLength = byteArray.Length;
using (Stream s = request.GetRequestStream())
{
s.Write(byteArray, 0, byteArray.Length);
}
string json = "";
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (WebException e)
{
response = e.Response;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "An error has occurred!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
using (StreamReader sr = new StreamReader(stream))
{
while (!sr.EndOfStream)
{
json += sr.ReadLine();
}
}
}
dynamic res = JsonDeserialize(json);
if (!ParseForError(res))
{
result = res;
return true;
}
result = null;
return false;
}
public bool ParseForError(dynamic result)
{
if (result.error != null)
{
int id = result.id;
string data = result.error.data;
string message = result.error.message;
int code = result.error.code;
if (id != 0 && !string.IsNullOrEmpty(data) && !string.IsNullOrEmpty(message) && code != 0)
{
LeError error = new LeError { Id = id, Code = code, Message = message, Data = data };
Errors.List.Add(error);
}
return true;
}
return false;
}
public dynamic JsonDeserialize(string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
dynamic entry = jss.Deserialize(json, typeof(object));
return entry;
}
}
public class LeEmpire
{
}
}
namespace Objects
{
public class Apikey
{
public const string Public = @"e10b8f94-e5a9-4175-8542-94b545e2de7b";
//private const string Private = @"eb3f0149-2c15-4fac-9390-3ed033e65a4d";
}
public class LeServer
{
public string Name { get; set; }
public string Uri { get; set; }
public string Status { get; set; }
public string Location { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public LeServer()
{
Name = "NOT SET";
Uri = "NOT SET";
Status = "NOT SET";
Location = "NOT SET";
Type = "NOT SET";
Description = "NOT SET";
}
}
public class LeServerInfo
{
public int RPC_Limit { get; set; }
public decimal Version { get; set; }
public string Time { get; set; }
public LeStarMapSize Star_Map_Size { get; set; }
public LeServerInfo()
{
RPC_Limit = 0;
Version = 0;
Time = "NOT SET";
Star_Map_Size = new LeStarMapSize();
}
}
public class LeStarMapSize
{
public int[] Y { get; set; }
public int[] X { get; set; }
public LeStarMapSize()
{
Y = new int[2];
X = new int[2];
}
}
public class LeJson
{
public double jsonrpc { get { return 2.0; } }
public int id { get { return 1; } }
public string method { get; set; }
public object[] parms { get; set; }
public LeJson(string action, object[] parm)
{
method = action;
parms = parm;
}
}
public class LeLogin
{
private string name { get; set; }
private string password { get; set; }
public string[] parms;
private static string Api_Key { get { return Apikey.Public; } }
public LeLogin(string user, string pass)
{
name = user;
password = pass;
parms = new[] { name, password, Api_Key };
}
}
public class LeSession
{
public string Session_Id { get; set; }
public LeStatus Status { get; set; }
public LeSession()
{
Session_Id = "NOT SET";
Status = new LeStatus();
}
}
public class LeStatus
{
public LeEmpire Empire { get; set; }
public LeServerInfo Server { get; set; }
public LeStatus()
{
Empire = new LeEmpire();
Server = new LeServerInfo();
}
}
public class LeEmpire
{
public int RPC_Count { get; set; }
public string Has_New_Message { get; set; }
public List<LePlanet> Planets { get; set; }
public string Self_Destruct_Active { get; set; }
public string Name { get; set; }
public string Status_Message { get; set; }
public string Self_Destruct_Date { get; set; }
public string Most_Recent_Message { get; set; }
public string Is_Isolationist { get; set; }
public string Home_Planet_ID { get; set; }
public string ID { get; set; }
public string Essentia { get; set; }
public LeEmpire()
{
RPC_Count = 0;
Has_New_Message = "NOT SET";
Planets = new List<LePlanet>();
Self_Destruct_Active = "NOT SET";
Name = "NOT SET";
Status_Message = "NOT SET";
Self_Destruct_Date = "NOT SET";
Most_Recent_Message = "NOT SET";
Is_Isolationist = "NOT SET";
Home_Planet_ID = "NOT SET";
ID = "NOT SET";
Essentia = "NOT SET";
}
}
public class LePlanet
{
public string ID { get; set; }
public string Name { get; set; }
public LePlanet()
{
ID = "NOT SET";
Name = "NOT SET";
}
}
}
namespace Administration
{
public class LeAdmin
{
public Traffic Cop { get; set; }
public List<LeServer> Servers { get; set; }
public LeSession Session { get; set; }
public LeLogin Login { get; set; }
public LeAdmin()
{
Servers = new List<LeServer>();
Session = new LeSession();
GetServers();
}
public LeSession EmpireLogin(string username, string password)
{
Traffic cop = new Traffic();
LeLogin login = new LeLogin(username, password);
LeJson lejson = new LeJson("login", login.parms);
string json = cop.CompileJsonString(lejson);
dynamic result;
if (cop.JsonPost(@"http://us1.lacunaexpanse.com/empire", json, out result))
{
Session = new LeSession();
Session.Session_Id = result.result.session_id;
Session.Status.Empire.RPC_Count = result.result.status.empire.rpc_count;
Session.Status.Empire.Has_New_Message = result.result.status.empire.has_new_messages;
foreach (string s in result.result.status.empire.planets.ToString().Replace(@"""", "").Replace(@"{", "").Replace(@"}", "").Split(','))
{
string[] plt = s.Split(':');
LePlanet planet = new LePlanet();
planet.ID = plt[0];
planet.Name = plt[1];
Session.Status.Empire.Planets.Add(planet);
}
Session.Status.Empire.Self_Destruct_Active = result.result.status.empire.self_destruct_active;
Session.Status.Empire.Name = result.result.status.empire.name;
Session.Status.Empire.Status_Message = result.result.status.empire.status_message;
Session.Status.Empire.Self_Destruct_Date = result.result.status.empire.self_destruct_date;
Session.Status.Empire.Most_Recent_Message = result.result.status.empire.most_recent_message;
Session.Status.Empire.Is_Isolationist = result.result.status.empire.is_isolationist;
Session.Status.Empire.Home_Planet_ID = result.result.status.empire.home_planet_id;
Session.Status.Empire.ID = result.result.status.empire.id;
Session.Status.Empire.Essentia = result.result.status.empire.essentia;
Session.Status.Server.RPC_Limit = result.result.status.server.rpc_limit;
Session.Status.Server.Version = result.result.status.server.version;
Session.Status.Server.Time = result.result.status.server.time;
Session.Status.Server.Star_Map_Size = new JavaScriptSerializer().Deserialize<LeStarMapSize>(result.result.status.server.star_map_size.ToString());
return Session;
}
return null;
}
public List<LeServer> GetServers()
{
Servers.Clear();
dynamic svrs = Traffic.JsonGet(@"http://www.lacunaexpanse.com/servers.json");
foreach (dynamic svr in svrs)
{
LeServer server = new LeServer
{
Name = svr.name,
Uri = svr.uri,
Status = svr.status,
Location = svr.location,
Type = svr.type,
Description = svr.description
};
Servers.Add(server);
}
return Servers;
}
}
}
namespace Objects
{
public class Status
{
public Server Server { get; set; }
public Empire Empire { get; set; }
public Body Body { get; set; }
}
public class Server
{
public DateTime Time { get; set; }
public decimal Version { get; set; }
public int Announcement { get; set; }
public int RPC_Limit { get; set; }
public Star_Map_Size Star_Map_Size { get; set; }
}
public class Star_Map_Size
{
public int[] X { get; set; }
public int[] y { get; set; }
public int[] z { get; set; }
}
public class Empire
{
}
public class Body
{
}
#region Empire
public class Session
{
}
public class Captcha
{
}
public class CreateParams
{
public string name { get; set; }
public string password { get; set; }
public string password1 { get; set; }
public string captcha_guid { get; set; }
public string captcha_solution { get; set; }
public string email { get; set; }
public string facebook_uid { get; set; }
public string facebook_token { get; set; }
public string invite_code { get; set; }
}
#endregion
#region Alliance
public class Alliance
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Alliances
{
public List<Alliance> List { get; set; }
}
public class AllianceProfile
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Leader_Id { get; set; }
public DateTime Date_Created { get; set; }
public AllianceMembers Members { get; set; }
public SpaceStations Space_Stations { get; set; }
public int Influence { get; set; }
}
public class AllianceMember
{
public int Id { get; set; }
public string Name { get; set; }
}
public class AllianceMembers
{
public List<AllianceMember> Members { get; set; }
}
public class SpaceStation
{
public int Id { get; set; }
public string Name { get; set; }
public int X { get; set; }
public int Y { get; set; }
}
public class SpaceStations
{
public List<SpaceStation> Stations { get; set; }
}
#endregion
#region Inbox
public class Message
{
public int Id { get; set; }
public string From { get; set; }
public int From_ID { get; set; }
public string To { get; set; }
public int To_id { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public DateTime Date { get; set; }
public bool Has_Read { get; set; }
public bool Has_Replied { get; set; }
public bool Has_Archived { get; set; }
public bool Has_Trashed { get; set; }
public string In_Reply_To { get; set; }
public string[] Recipients { get; set; }
public string[] Tags { get; set; }
public string Attachments { get; set; }
}
public class Messages
{
public List<Message> List { get; set; }
}
public class InboxOptions
{
public int Page_Number { get; set; }
public List<InboxTag> Tags { get; set; }
}
public class InboxTag
{
public string Tag { get; set; }
}
#endregion
}
namespace Empire
{
public class EmpireCalls
{
public bool IsNameAvailable(string name)
{
return false;
}
public bool Logout(Guid session_id)
{
return false;
}
public Session Login(string username, string password)
{
return null;
}
public Captcha FetchCaptcha()
{
return null;
}
public int Create(LELibrary.Objects.CreateParams parms)
{
return -4000;
}
public int Found(int empire_id, Guid api_key)
{
return -4000;
}
public string GetInviteFriendURL(Guid session_id)
{
return null;
}
public void InviteFriend(Guid session_id, string email, string customMsg)
{
}
}
}
namespace Alliance
{
public class Alliance
{
public AllianceProfile ViewProfile(Guid session_id, int alliance_id)
{
return null;
}
public Alliances Find(Guid session_id, string name)
{
return null;
}
}
}
namespace Inbox
{
public class Inbox
{
public Messages ViewInbox(Guid session_id, InboxOptions options)
{
return null;
}
}
}
namespace Stats
{
}
namespace Map
{
}
namespace Body
{
}
namespace Buildings
{
}
namespace Payments
{
}
namespace Chat
{
}
namespace Announcement
{
}
namespace Captcha
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment