Exemplo n.º 1
0
        public void WritePeristentState()
        {
            if (WritingState)
            {
                return;
            }
            WritingState = true;
            var preLastPersistentStateWrite = LastPersistentStateWrite;

            LastPersistentStateWrite = DistanceServerMain.UnixTime;
            var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/ChatFilterState.json");

            try
            {
                var writer = new JsonFx.Json.JsonWriter();
                var text   = writer.Write(new { TempMuted, PlayerLevels });
                System.IO.File.WriteAllText(filePath.FullName, text);
            }
            catch (Exception e)
            {
                LastPersistentStateWrite = preLastPersistentStateWrite;
                Log.Error($"Couldn't write ChatFilterState.json: {e}");
            }
            WritingState = false;
        }
Exemplo n.º 2
0
        internal void RespondChat()
        {
            var writer = new JsonFx.Json.JsonWriter();

            if (!IsPrivateMode || DistancePlayer == null)
            {
                Context.Response.StatusCode        = 401;
                Context.Response.StatusDescription = "Unauthorized";
                Response = writer.Write(new
                {
                    ErrorCode = 401,
                });
                return;
            }
            var    reader  = new JsonFx.Json.JsonReader();
            var    data    = (Dictionary <string, object>)reader.Read(Body);
            string message = (string)data["Message"];

            var chatColor = "[" + Distance::ColorEx.ColorToHexNGUI(Distance::ColorEx.PlayerRainbowColor(DistancePlayer.Index)) + "]";

            Plugin.Server.SayChat(new DistanceChat(chatColor + DistancePlayer.Name + "[FFFFFF]: " + message + "[-]")
            {
                SenderGuid      = DistancePlayer.UnityPlayerGuid,
                ChatType        = DistanceChat.ChatTypeEnum.PlayerChatMessage,
                ChatDescription = "HttpServer:PlayerChat"
            });

            Response = writer.Write(new
            {
                Success = true,
            });
        }
Exemplo n.º 3
0
        internal void RespondLink()
        {
            var writer = new JsonFx.Json.JsonWriter();

            if (!IsPrivateMode)
            {
                Context.Response.StatusCode        = 401;
                Context.Response.StatusDescription = "Unauthorized";
                Response = writer.Write(new
                {
                    ErrorCode = 401,
                });
                return;
            }
            var    reader = new JsonFx.Json.JsonReader();
            var    data   = (Dictionary <string, object>)reader.Read(Body);
            string guid   = (string)data["Guid"];

            Plugin.Links[SessionId] = guid;
            Response = writer.Write(new
            {
                Success = true,
            });

            if (data.ContainsKey("SendIpWarning") && (bool)data["SendIpWarning"])
            {
                var player = Plugin.Manager.Server.GetDistancePlayer(guid);
                if (player != null)
                {
                    Plugin.Server.SayLocalChat(player.UnityPlayer, DistanceChat.Server("HttpServer:Link", "Your game session has been automatically linked with a web session. You can now vote and chat from the website.\nIf this wasn't you, type [00FFFF]/unlink[-]"));
                }
            }
        }
Exemplo n.º 4
0
        public void JsonFx_POCO()
        {
            var jsr = new JsonFx.Json.JsonReader();
            var jsw = new JsonFx.Json.JsonWriter();

            var f = new Foo {
                Name = "peter", Age = 42, TooOld = false
            };

            f.Bars = new List <Bar>();
            f.Bars.Add(new Bar()
            {
                Str = "Isestr", Ort = "Hamburg"
            });
            var json = jsw.Write(f);

            Console.WriteLine(json);

            dynamic df = jsr.Read(json);

            Assert.AreEqual("peter", df.Name);
            Assert.IsFalse(df.TooOld);
            Assert.AreEqual(1, df.Bars.Length);


            var foo = jsr.Read <Foo>(json);

            Console.WriteLine(foo.Name);
        }
Exemplo n.º 5
0
        public static string ToJson(this object obj)
        {
            var writer = new JsonFx.Json.JsonWriter();
            var json   = writer.Write(obj);

            return(PrettifyJson(json));
        }
        public void JsonFx_Expando()
        {
            var jsr = new JsonFx.Json.JsonReader();
            var jsw = new JsonFx.Json.JsonWriter();

            dynamic cmd = new ExpandoObject();
            cmd.cmd = "Anzeigen";
            dynamic frage = new ExpandoObject();
            frage.Text = "Welches Tier ist kein Säugetier?";
            cmd.payload = frage;

            var antwortoptionen = new List<dynamic>();
            dynamic antwortoption = new ExpandoObject();
            antwortoption.Text = "Hund";
            antwortoption.IstKorrekt = false;
            antwortoptionen.Add(antwortoption);
            antwortoption = new ExpandoObject();
            antwortoption.Text = "Ameise";
            antwortoption.IstKorrekt = true;
            antwortoptionen.Add(antwortoption);
            frage.Antwortoptionen = antwortoptionen;

            var json = jsw.Write(cmd);
            Console.WriteLine(json);

            dynamic dc = jsr.Read(json);
            Console.WriteLine(dc.cmd);
            Console.WriteLine(dc.payload.Text);
            foreach (dynamic ao in dc.payload.Antwortoptionen)
                Console.WriteLine("  {0}, {1}", ao.Text, ao.IstKorrekt);
        }
Exemplo n.º 7
0
        public static void SaveSettings()
        {
            lock (LockerObject)
            {
                // No settings to save?  Don't save anything.
                if (_settings == null)
                {
                    return;
                }

                var dataWriterSettings = new DataWriterSettings
                {
                    PrettyPrint = true,
                };

                if (System.IO.File.Exists(_filePath))
                {
                    System.IO.File.Delete(_filePath);
                }
                using (var fileStream = System.IO.File.Open(_filePath, FileMode.CreateNew, FileAccess.Write))
                {
                    using (TextWriter tw = new StreamWriter(fileStream))
                    {
                        var jsonWriter = new JsonFx.Json.JsonWriter(dataWriterSettings);
                        jsonWriter.Write(_settings, tw);
                    }
                }
            }
        }
Exemplo n.º 8
0
        internal void RespondServerChat()
        {
            var writer = new JsonFx.Json.JsonWriter();

            if (!IsPrivateMode)
            {
                Context.Response.StatusCode        = 401;
                Context.Response.StatusDescription = "Unauthorized";
                Response = writer.Write(new
                {
                    ErrorCode = 401,
                });
                return;
            }
            var    reader  = new JsonFx.Json.JsonReader();
            var    data    = (Dictionary <string, object>)reader.Read(Body);
            string message = (string)data["Message"];
            object sender  = "server";

            data.TryGetValue("Sender", out sender);

            Plugin.Server.SayChat(new DistanceChat(message)
            {
                SenderGuid      = (string)sender,
                ChatType        = DistanceChat.ChatTypeEnum.ServerCustom,
                ChatDescription = "HttpServer:ServerChat"
            });

            Response = writer.Write(new
            {
                Success = true,
            });
        }
Exemplo n.º 9
0
        private static List <string> SerializeWithJsonFx <T>(List <T> objects)
        {
            var writer = new JsonFxWriter();

            var jsonStrings = objects.Select(o => writer.Write(o)).ToList();

            return(jsonStrings);
        }
Exemplo n.º 10
0
        public JsonResult GetCups()
        {
            dynamic cupsTable = new CupTotals();
            var cups = cupsTable.All(OrderBy: "name");

            var jsonWriter = new JsonFx.Json.JsonWriter();
            string jsonFX = jsonWriter.Write(cups);

            return Json(jsonFX, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 11
0
        public void savedisequiplist()
        {
            string content = "";

            content = new JsonFx.Json.JsonWriter().Write(dis_equip_list);
            if (content != "")
            {
                System.IO.File.WriteAllText(DISLISTEQUIP_FILE_NAME, content);
            }
        }
Exemplo n.º 12
0
        public void SendJson <T>(T body)
        {
            var writer         = new JsonFx.Json.JsonWriter();
            var serializedData = writer.Write(body);

            byte[] buf = Encoding.UTF8.GetBytes(serializedData);
            AddHeader("Content-Type", "text/json");
            AddHeader("Content-Length", buf.Length.ToString());
            SendBody(buf);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Serializes the object to a JSON string, and writes it to the current stream.
        /// </summary>
        /// <remarks>If the object cannot be serialized, an exception is thrown.</remarks>
        public static void WriteJson <T>(this HttpListenerResponse response, T obj)
        {
            var writer         = new JsonFx.Json.JsonWriter();
            var serializedData = writer.Write(obj);

            byte[] buf = Encoding.UTF8.GetBytes(serializedData);
            response.ContentType     = "text/json";
            response.ContentLength64 = buf.Length;
            response.OutputStream.Write(buf, 0, buf.Length);
        }
Exemplo n.º 14
0
        public override void WriteContent(HttpListenerResponse response)
        {
            var writer         = new JsonFx.Json.JsonWriter();
            var serializedData = writer.Write(_content);

            byte[] buf = Encoding.UTF8.GetBytes(serializedData);

            response.StatusCode      = (int)_statusCode;
            response.ContentType     = "text/json";
            response.ContentLength64 = buf.Length;
            response.OutputStream.Write(buf, 0, buf.Length);
        }
Exemplo n.º 15
0
        public void Save(bool formatJson = true)
        {
            DataWriterSettings st = new DataWriterSettings {
                PrettyPrint = formatJson
            };
            var writer = new JsonFx.Json.JsonWriter(st);

            using (var sw = new StreamWriter(FilePath, false))
            {
                sw.WriteLine(writer.Write(this));
            }
        }
Exemplo n.º 16
0
        /*public static T DeserializeUsingJSONFx<T>(string message)
         * {
         *  object retMessage;
         *  var reader = new JsonFx.Json.JsonReader();
         *  retMessage = reader.Read<T>(message);
         *  return (T)retMessage;
         * }*/

        /// <summary>
        /// Serialize the specified message using either JSONFX or NEWTONSOFT.JSON.
        /// The functionality is based on the pre-compiler flag
        /// </summary>
        /// <param name="message">Message.</param>
        public static string Serialize(object message)
        {
            string retMessage;

            #if (USE_JSONFX)
            var writer = new JsonFx.Json.JsonWriter();
            retMessage = writer.Write(message);
            retMessage = ConvertHexToUnicodeChars(retMessage);
            #else
            retMessage = JsonConvert.SerializeObject(message);
            #endif
            return(retMessage);
        }
Exemplo n.º 17
0
        public void Serialize <T>(T message, Stream dest) where T : class
        {
            MessagePackage package = new MessagePackage();

            package.name       = message.GetType().FullName;
            package.serialized = JsonFx.Json.JsonWriter.Serialize(message);
            var jsonWriter = new JsonFx.Json.JsonWriter(dest);

            jsonWriter.Write(package);
            jsonWriter.TextWriter.Flush();
            //dest.Write(JsonFx.Json.JsonWriter.Serialize(package));
            dest.Flush();
        }
Exemplo n.º 18
0
        /// <summary>
        /// Send an error response as a WebSocket JSON packet.
        /// </summary>
        /// <param name="error">Error message.</param>
        /// <param name="name">Class name. Default is the name given
        /// <param name="type">Error type.</param>
        /// in the handler's constructor.</param>
        public void SendErrorPacket(string error, string name = null, string type = "error")
        {
            if (name == null)
            {
                name = Name;
            }
            var body = new Dictionary <string, Dictionary <string, string> > {
                { "error", new Dictionary <string, string> {
                      { name, error },
                      { "type", type },
                  } },
            };
            var writer = new JsonFx.Json.JsonWriter();

            this.EnqueueMessage(writer.Write(body));
        }
        public static void Create(string name, Guid guid, string dllPath, IDictionary <string, object> resourceList, string actionPath,
                                  dynamic menuFormat, Platform.ComRegisterClass.RightClickContextMenuOptions[] association, string[] fileExtensionFilter, bool expandFileNames)
        {
            AssemblyName myAsmName = new AssemblyName(System.IO.Path.GetFileNameWithoutExtension(dllPath));

            myAsmName.CodeBase             = String.Concat("file:///", System.IO.Path.GetDirectoryName(dllPath));
            myAsmName.CultureInfo          = new System.Globalization.CultureInfo("en-US");
            myAsmName.KeyPair              = new StrongNameKeyPair(CreateKeyPair(System.IO.Path.GetFileNameWithoutExtension(dllPath), 1024));
            myAsmName.Flags                = AssemblyNameFlags.PublicKey;
            myAsmName.VersionCompatibility = AssemblyVersionCompatibility.SameProcess;
            myAsmName.HashAlgorithm        = AssemblyHashAlgorithm.SHA1;
            myAsmName.Version              = new Version("1.0.0.0");

            AssemblyBuilder myAsmBuilder  = AppDomain.CurrentDomain.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.Save, System.IO.Path.GetDirectoryName(dllPath));
            ModuleBuilder   myModBuilder  = myAsmBuilder.DefineDynamicModule("MyModule", System.IO.Path.GetFileName(dllPath));
            TypeBuilder     myTypeBuilder = myModBuilder.DefineType("MyType", TypeAttributes.Public, typeof(MenuExtension));

            var menuFormatWriter = new JsonFx.Json.JsonWriter();
            var menuFormatJson   = menuFormatWriter.Write(menuFormat);

            AddAttribute(myTypeBuilder, typeof(ComVisibleAttribute), true);
            AddAttribute(myTypeBuilder, typeof(GuidAttribute), guid.ToString());
            AddAttribute(myAsmBuilder, typeof(GuidAttribute), guid.ToString());
            AddAttribute(myAsmBuilder, typeof(InfoStorageAttribute), name, actionPath, menuFormatJson, association, fileExtensionFilter, expandFileNames);

            // embed all images found in the menu into the assembly
            foreach (string keyname in resourceList.Keys)
            {
                string filename = (string)resourceList[keyname];
                System.Drawing.Image   image     = System.Drawing.Image.FromFile(filename);
                System.IO.MemoryStream memStream = new System.IO.MemoryStream();
                image.Save(memStream, System.Drawing.Imaging.ImageFormat.Bmp);
                byte[] rawdata = memStream.ToArray();
                System.Resources.IResourceWriter rw = myModBuilder.DefineResource(keyname + ".resources", "description", ResourceAttributes.Public);
                rw.AddResource("image.bmp", rawdata);
            }

            myTypeBuilder.CreateType();
            myModBuilder.CreateGlobalFunctions();

            myAsmBuilder.Save(System.IO.Path.GetFileName(dllPath));
        }
Exemplo n.º 20
0
        public void JsonFx_POCO()
        {
            var jsr = new JsonFx.Json.JsonReader();
            var jsw = new JsonFx.Json.JsonWriter();

            var f = new Foo { Name = "peter", Age = 42, TooOld = false };
            f.Bars = new List<Bar>();
            f.Bars.Add(new Bar(){Str = "Isestr", Ort = "Hamburg"});
            var json = jsw.Write(f);
            Console.WriteLine(json);

            dynamic df = jsr.Read(json);
            Assert.AreEqual("peter", df.Name);
            Assert.IsFalse(df.TooOld);
            Assert.AreEqual(1, df.Bars.Length);


            var foo = jsr.Read<Foo>(json);
            Console.WriteLine(foo.Name);
        }
		public static void Create( string name, Guid guid, string dllPath, IDictionary<string, object> resourceList, string actionPath,
			dynamic menuFormat, Platform.ComRegisterClass.RightClickContextMenuOptions[] association, string[] fileExtensionFilter, bool expandFileNames )
		{
			AssemblyName myAsmName = new AssemblyName( System.IO.Path.GetFileNameWithoutExtension( dllPath ) );
			myAsmName.CodeBase = String.Concat( "file:///", System.IO.Path.GetDirectoryName( dllPath ) );
			myAsmName.CultureInfo = new System.Globalization.CultureInfo( "en-US" );
			myAsmName.KeyPair = new StrongNameKeyPair( CreateKeyPair( System.IO.Path.GetFileNameWithoutExtension( dllPath ), 1024 ) );
			myAsmName.Flags = AssemblyNameFlags.PublicKey;
			myAsmName.VersionCompatibility = AssemblyVersionCompatibility.SameProcess;
			myAsmName.HashAlgorithm = AssemblyHashAlgorithm.SHA1;
			myAsmName.Version = new Version( "1.0.0.0" );

			AssemblyBuilder myAsmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Save, System.IO.Path.GetDirectoryName( dllPath ) );
			ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule( "MyModule", System.IO.Path.GetFileName( dllPath ) );
			TypeBuilder myTypeBuilder = myModBuilder.DefineType( "MyType", TypeAttributes.Public, typeof( MenuExtension ) );

			var menuFormatWriter = new JsonFx.Json.JsonWriter();
			var menuFormatJson = menuFormatWriter.Write( menuFormat );

			AddAttribute( myTypeBuilder, typeof( ComVisibleAttribute ), true );
			AddAttribute( myTypeBuilder, typeof( GuidAttribute ), guid.ToString() );
			AddAttribute( myAsmBuilder, typeof( GuidAttribute ), guid.ToString() );
			AddAttribute( myAsmBuilder, typeof( InfoStorageAttribute ), name, actionPath, menuFormatJson, association, fileExtensionFilter, expandFileNames );

			// embed all images found in the menu into the assembly
			foreach ( string keyname in resourceList.Keys )
			{
				string filename = (string)resourceList[ keyname ];
				System.Drawing.Image image = System.Drawing.Image.FromFile( filename );
				System.IO.MemoryStream memStream = new System.IO.MemoryStream();
				image.Save( memStream, System.Drawing.Imaging.ImageFormat.Bmp );
				byte[] rawdata = memStream.ToArray();
				System.Resources.IResourceWriter rw = myModBuilder.DefineResource( keyname + ".resources", "description", ResourceAttributes.Public );
				rw.AddResource( "image.bmp", rawdata );
			}

			myTypeBuilder.CreateType();
			myModBuilder.CreateGlobalFunctions();

			myAsmBuilder.Save( System.IO.Path.GetFileName( dllPath ) );
		}
Exemplo n.º 22
0
        internal void RespondVote()
        {
            var writer = new JsonFx.Json.JsonWriter();

            if (!IsPrivateMode || DistancePlayer == null)
            {
                Context.Response.StatusCode        = 401;
                Context.Response.StatusDescription = "Unauthorized";
                Response = writer.Write(new
                {
                    ErrorCode = 401,
                });
                return;
            }

            Response = writer.Write(new
            {
                Success = false,
                Reason  = "Not implemented",
            });
        }
Exemplo n.º 23
0
        internal void RespondLinks()
        {
            var writer = new JsonFx.Json.JsonWriter();

            if (!IsPrivateMode)
            {
                Context.Response.StatusCode        = 401;
                Context.Response.StatusDescription = "Unauthorized";
                Response = writer.Write(new
                {
                    ErrorCode = 401,
                });
                return;
            }
            Response = writer.Write(new
            {
                CodesForward = Plugin.CodesForward,
                CodesReverse = Plugin.CodesReverse,
                Links        = Plugin.Links,
            });
        }
Exemplo n.º 24
0
        public void JsonFx_Expando()
        {
            var jsr = new JsonFx.Json.JsonReader();
            var jsw = new JsonFx.Json.JsonWriter();

            dynamic cmd = new ExpandoObject();

            cmd.cmd = "Anzeigen";
            dynamic frage = new ExpandoObject();

            frage.Text  = "Welches Tier ist kein Säugetier?";
            cmd.payload = frage;

            var     antwortoptionen = new List <dynamic>();
            dynamic antwortoption   = new ExpandoObject();

            antwortoption.Text       = "Hund";
            antwortoption.IstKorrekt = false;
            antwortoptionen.Add(antwortoption);
            antwortoption            = new ExpandoObject();
            antwortoption.Text       = "Ameise";
            antwortoption.IstKorrekt = true;
            antwortoptionen.Add(antwortoption);
            frage.Antwortoptionen = antwortoptionen;

            var json = jsw.Write(cmd);

            Console.WriteLine(json);

            dynamic dc = jsr.Read(json);

            Console.WriteLine(dc.cmd);
            Console.WriteLine(dc.payload.Text);
            foreach (dynamic ao in dc.payload.Antwortoptionen)
            {
                Console.WriteLine("  {0}, {1}", ao.Text, ao.IstKorrekt);
            }
        }
Exemplo n.º 25
0
        internal void RespondLinkReverse()
        {
            var writer = new JsonFx.Json.JsonWriter();

            if (!IsPrivateMode)
            {
                Context.Response.StatusCode        = 401;
                Context.Response.StatusDescription = "Unauthorized";
                Response = writer.Write(new
                {
                    ErrorCode = 401,
                });
                return;
            }

            foreach (var pair in Plugin.CodesReverse)
            {
                if (pair.Value == SessionId)
                {
                    Response = writer.Write(new
                    {
                        Code = pair.Key,
                    });
                    return;
                }
            }

            var code = Entry.GenerateCode();

            Plugin.CodesReverse[code] = SessionId;

            Response = writer.Write(new
            {
                Code = code,
            });
        }
Exemplo n.º 26
0
        protected Request Request(Method method, string segments, Object data)
        {
            var request = new RestRequest(segments, method);

            foreach (var header in this.GetHeaders())
            {
                request.AddHeader(header.Key, header.Value);
            }

            // Always exchange data using JSON
            request.RequestFormat = DataFormat.Json;

            if (method == Method.GET)
            {
                var writer = new JsonFx.Json.JsonWriter();
                request.Resource += "?" + writer.Write(data);
            }
            else
            {
                request.AddBody(data);
            }

            return(new Request(rest, request));
        }
Exemplo n.º 27
0
        public static string SerializeJsonFx <T>(T obj)
        {
            var writer = new JsonFx.Json.JsonWriter(JsonFxWriterSettings);

            return(writer.Write(obj));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Encode an object as JSON and send it to the client,
        /// without encapsulating it in {name:object}.
        /// </summary>
        /// <param name="body">Object to send.</param>
        /// <typeparam name="T">The object type.</typeparam>
        public void SendUnencapsulatedJson <T>(T body)
        {
            var writer = new JsonFx.Json.JsonWriter();

            handler.EnqueueMessage(writer.Write(body));
        }
Exemplo n.º 29
0
        protected Request Request(Method method, string segments, Object data)
        {
            var request = new RestRequest (segments, method);

            foreach (var header in this.GetHeaders()) {
                request.AddHeader (header.Key, header.Value);
            }

            // Always exchange data using JSON
            request.RequestFormat = DataFormat.Json;

            if (method == Method.GET) {
                var writer = new JsonFx.Json.JsonWriter ();
                request.Resource += "?" + writer.Write (data);
            } else {
                request.AddBody (data);
            }

            return new Request(rest, request);
        }
Exemplo n.º 30
0
 public void savedisshiplist()
 {
     string content = "";
     content = new JsonFx.Json.JsonWriter().Write(dis_ship_list);
     if(content != "")
     {
         System.IO.File.WriteAllText(DISLIST_FILE_NAME, content);
     }
 }
Exemplo n.º 31
0
        public override string ToString()
        {
            var w = new JsonFx.Json.JsonWriter();

            return(w.Write(this.members));
        }
Exemplo n.º 32
0
        private void StoreCredenials()
        {
            var j = new JsonFx.Json.JsonWriter().Write(_credentials);

            File.WriteAllText(_path, j);
        }
Exemplo n.º 33
0
        internal void RespondPlaylist()
        {
            var server = DistanceServerMain.Instance.Server;
            var writer = new JsonFx.Json.JsonWriter();

            var autoServer = DistanceServerMain.Instance.GetPlugin <BasicAutoServer.BasicAutoServer>();

            if (autoServer == null)
            {
                Response = writer.Write(new
                {
                    CurrentLevelIndex = 0,
                    Playlist          = new
                    {
                        Total  = 0,
                        Start  = 0,
                        Count  = 0,
                        Levels = new string[] { },
                    },
                });
                return;
            }

            var query = new Dictionary <string, string>();

            foreach (var key in Context.Request.QueryString.AllKeys)
            {
                query.Add(key, Context.Request.QueryString[key]);
            }

            int    start    = autoServer.currentLevelIndex;
            int    count    = 10;
            string startStr = "";
            string countStr = "";

            query.TryGetValue("Start", out startStr);
            query.TryGetValue("Count", out countStr);
            int.TryParse(startStr, out start);
            int.TryParse(countStr, out count);

            var levels = new List <LevelJsonData>();

            for (int i = start; i < start + count; i++)
            {
                if (i >= autoServer.Playlist.Count)
                {
                    break;
                }
                var level     = autoServer.Playlist[i];
                var jsonLevel = new LevelJsonData();
                jsonLevel.Index             = i;
                jsonLevel.Name              = level.Name;
                jsonLevel.RelativeLevelPath = level.RelativeLevelPath;
                jsonLevel.WorkshopFileId    = level.WorkshopFileId;
                jsonLevel.GameMode          = level.GameMode;
                levels.Add(jsonLevel);
            }

            Response = writer.Write(new
            {
                CurrentLevelIndex = autoServer.currentLevelIndex,
                Playlist          = new
                {
                    Total  = autoServer.Playlist.Count,
                    Start  = start,
                    Count  = count,
                    Levels = levels,
                },
            });
        }
Exemplo n.º 34
0
        public static void SaveSettings()
        {
            lock (LockerObject)
            {
                // No settings to save?  Don't save anything.
                if (_settings == null) { return; }

                var dataWriterSettings = new DataWriterSettings
                {
                    PrettyPrint = true,
                };

                if (System.IO.File.Exists(_filePath))
                {
                    System.IO.File.Delete(_filePath);
                }
                using (var fileStream = System.IO.File.Open(_filePath, FileMode.CreateNew, FileAccess.Write))
                {
                    using (TextWriter tw = new StreamWriter(fileStream))
                    {
                        var jsonWriter = new JsonFx.Json.JsonWriter(dataWriterSettings);
                        jsonWriter.Write(_settings, tw);
                    }
                }
            }
        }
Exemplo n.º 35
0
        internal void RespondSummary()
        {
            Log.DebugLine("HTTP INFO SUMMARY", 0);
            var server = DistanceServerMain.Instance.Server;
            var writer = new JsonFx.Json.JsonWriter();

            var players = new List <PlayerJsonData>(server.DistancePlayers.Count);

            foreach (var player in server.DistancePlayers.Values)
            {
                var jsonPlayer = new PlayerJsonData();
                jsonPlayer.UnityPlayerGuid        = player.UnityPlayerGuid;
                jsonPlayer.State                  = player.State;
                jsonPlayer.Stuck                  = player.Stuck;
                jsonPlayer.LevelId                = player.LevelId;
                jsonPlayer.ReceivedInfo           = player.ReceivedInfo;
                jsonPlayer.Index                  = player.Index;
                jsonPlayer.Name                   = player.Name;
                jsonPlayer.JoinedAt               = player.JoinedAt;
                jsonPlayer.ValidatedAt            = player.ValidatedAt;
                jsonPlayer.Ready                  = player.Ready;
                jsonPlayer.LevelCompatibilityInfo = player.LevelCompatibilityInfo;
                jsonPlayer.LevelCompatibility     = player.LevelCompatability.ToString();
                jsonPlayer.Valid                  = player.Valid;
                if (IsPrivateMode)
                {
                    jsonPlayer.IpAddress = player.UnityPlayer.ipAddress;
                    jsonPlayer.Port      = player.UnityPlayer.port;
                }
                else
                {
                    jsonPlayer.IpAddress = "Hidden";
                    jsonPlayer.Port      = -1;
                }
                if (player.Car != null)
                {
                    var car     = player.Car;
                    var jsonCar = new CarJsonData();
                    jsonCar.CarColors = new float[][] {
                        new float[] { car.CarColors.primary_.r, car.CarColors.primary_.g, car.CarColors.primary_.b, car.CarColors.primary_.a },
                        new float[] { car.CarColors.secondary_.r, car.CarColors.secondary_.g, car.CarColors.secondary_.b, car.CarColors.secondary_.a },
                        new float[] { car.CarColors.glow_.r, car.CarColors.glow_.g, car.CarColors.glow_.b, car.CarColors.glow_.a },
                        new float[] { car.CarColors.sparkle_.r, car.CarColors.sparkle_.g, car.CarColors.sparkle_.b, car.CarColors.sparkle_.a },
                    };
                    jsonCar.CarName         = car.CarName;
                    jsonCar.Points          = car.Points;
                    jsonCar.Finished        = car.Finished;
                    jsonCar.FinishData      = car.FinishData;
                    jsonCar.FinishType      = car.FinishType;
                    jsonCar.Spectator       = car.Spectator;
                    jsonCar.Alive           = car.Alive;
                    jsonCar.WingsOpen       = car.WingsOpen;
                    jsonCar.Position        = new float[] { car.Rigidbody.position.x, car.Rigidbody.position.y, car.Rigidbody.position.z };
                    jsonCar.Rotation        = new float[] { car.Rigidbody.rotation.w, car.Rigidbody.rotation.x, car.Rigidbody.rotation.y, car.Rigidbody.rotation.z };
                    jsonCar.Velocity        = new float[] { car.Rigidbody.velocity.x, car.Rigidbody.velocity.y, car.Rigidbody.velocity.z };
                    jsonCar.AngularVelocity = new float[] { car.Rigidbody.angularVelocity.x, car.Rigidbody.angularVelocity.y, car.Rigidbody.angularVelocity.z };
                    jsonPlayer.Car          = jsonCar;
                }
                players.Add(jsonPlayer);
            }

            AutoServerJsonData autoServerJson = null;
            var autoServer = DistanceServerMain.Instance.GetPlugin <BasicAutoServer.BasicAutoServer>();

            if (autoServer != null)
            {
                autoServerJson                = new AutoServerJsonData();
                autoServerJson.IdleTimeout    = autoServer.IdleTimeout;
                autoServerJson.LevelTimeout   = autoServer.LevelTimeout;
                autoServerJson.WelcomeMessage = autoServer.WelcomeMessage;
                autoServerJson.AdvanceWhenStartingPlayersFinish = autoServer.AdvanceWhenStartingPlayersFinish;
                autoServerJson.LevelEndTime        = DistanceServerMain.NetworkTimeToUnixTime(autoServer.LevelEndTime);
                autoServerJson.StartingPlayerGuids = autoServer.StartingPlayerGuids.ToArray();
            }

            Log.DebugLine("HTTP INFO SUMMARY", 1);
            VotingJsonData votingJsonData = null;

            try
            {
                votingJsonData = RespondSummaryVote();
            }
            catch (Exception e) { } // TODO
            Log.DebugLine("HTTP INFO SUMMARY", 2);

            var chatLog = new List <ChatJsonData>();

            foreach (var chat in server.ChatLog)
            {
                var chatJson = new ChatJsonData();
                chatJson.Timestamp   = chat.Timestamp;
                chatJson.Chat        = chat.Message;
                chatJson.Sender      = chat.SenderGuid;
                chatJson.Guid        = chat.ChatGuid;
                chatJson.Type        = chat.ChatType.ToString();
                chatJson.Description = chat.ChatDescription;
                chatLog.Add(chatJson);
            }

            Response = writer.Write(new
            {
                Server = new
                {
                    CurrentLevelId               = server.CurrentLevelId,
                    MaxPlayers                   = server.MaxPlayers,
                    Port                         = server.Port,
                    ReportToMasterServer         = server.ReportToMasterServer,
                    MasterServerGameModeOverride = server.MasterServerGameModeOverride,
                    DistanceVersion              = server.DistanceVersion,
                    IsInLobby                    = server.IsInLobby,
                    HasModeStarted               = server.HasModeStarted,
                    ModeStartTime                = DistanceServerMain.NetworkTimeToUnixTime(server.ModeStartTime),
                },
                Level = new
                {
                    Name = server.CurrentLevel.Name,
                    RelativeLevelPath = server.CurrentLevel.RelativeLevelPath,
                    WorkshopFileId    = server.CurrentLevel.WorkshopFileId,
                    GameMode          = server.CurrentLevel.GameMode,
                },
                ChatLog      = chatLog,
                Players      = players,
                AutoServer   = autoServerJson,
                VoteCommands = votingJsonData,
            });
        }