예제 #1
0
        object NewToken(RestVerbs verbs, IParameterCollection parameters)
        {
            var user = verbs["username"];
            var pass = verbs["password"];

            RestObject obj = null;
            if (Verify != null)
                obj = Verify(user, pass);

            if (obj == null)
                obj = new RestObject("401") { Error = "Invalid username/password combination provided. Please re-submit your query with a correct pair." };

            if (obj.Error != null)
                return obj;

            string hash;
            var rand = new Random();
            var randbytes = new byte[32];
            do
            {
                rand.NextBytes(randbytes);
                hash = randbytes.Aggregate("", (s, b) => s + b.ToString("X2"));
            } while (Tokens.ContainsKey(hash));

            Tokens.Add(hash, user);

            obj["token"] = hash;
            return obj;
        }
예제 #2
0
		public RestRequestArgs(RestVerbs verbs, IParameterCollection param, IRequest request, SecureRest.TokenData tokenData, IHttpContext context)
		{
			Verbs = verbs;
			Parameters = param;
			Request = request;
			TokenData = tokenData;
			Context = context;
		}
예제 #3
0
 private object ServerTokenTest(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     return(new RestObject()
     {
         { "response", "Token is valid and was passed through correctly." },
         { "associateduser", tokenData.Username }
     });
 }
예제 #4
0
        private object PlayerList(RestVerbs verbs, IParameterCollection parameters)
        {
            var activeplayers = Main.player.Where(p => null != p && p.active).ToList();

            return(new RestObject()
            {
                { "players", string.Join(", ", activeplayers.Select(p => p.name)) }
            });
        }
예제 #5
0
        //The Wizard example, for demonstrating the response convention:
        object Wizard(RestVerbs verbs, IParameterCollection parameters)
        {
            var returnBack = new Dictionary <string, string>();

            returnBack.Add("status", "200");                                                                                   //Keep this in everything, 200 = ok, etc. Standard http status codes.
            returnBack.Add("error", "(If this failed, you would have a different status code and provide the error object.)"); //And only include this if the status isn't 200 or a failure
            returnBack.Add("Verified Wizard", "You're a wizard, " + verbs["username"]);                                        //Outline any api calls and possible responses in some form of documentation somewhere
            return(returnBack);
        }
예제 #6
0
 private object WorldMeteor(RestVerbs verbs, IParameterCollection parameters)
 {
     if (null == WorldGen.genRand)
     {
         WorldGen.genRand = new Random();
     }
     WorldGen.dropMeteor();
     return(RestResponse("Meteor has been spawned"));
 }
예제 #7
0
        private object PlayerList(RestVerbs verbs, IParameterCollection parameters)
        {
            var    activeplayers  = Main.player.Where(p => p != null && p.active).ToList();
            string currentPlayers = string.Join(", ", activeplayers.Select(p => p.name));
            var    ret            = new RestObject("200");

            ret["players"] = currentPlayers;
            return(ret);
        }
예제 #8
0
        private object WorldMeteor(RestVerbs verbs, IParameterCollection parameters)
        {
            WorldGen.dropMeteor();
            var returnBlock = new Dictionary <string, string>();

            returnBlock.Add("status", "200");
            returnBlock.Add("response", "Meteor has been spawned.");
            return(returnBlock);
        }
예제 #9
0
        public void Ctor__CompositeKeyIncludesPathAndRoute()
        {
            const string    path   = SvcForMethods.PostPath;
            const RestVerbs method = SvcForMethods.PostMethod;
            var             route  = new RouteAttribute(path, method);

            var service = new RService(_options);

            service.Routes.Keys.Should().Contain(Utils.GetRouteKey(route));
        }
예제 #10
0
        /// <summary>
        /// Initializes an instance of <see cref="RouteAttribute"/>.
        /// </summary>
        /// <param name="path">Path template to map to request.</param>
        /// <param name="verbs">A list of flags of HTTP verbs supported by the service.</param>
        /// <remarks>If no verbs are specified GET, POST, PUT, PATCH, DELETE and OPTIONS are routed.</remarks>
        public RouteAttribute(String path, RestVerbs verbs = RestVerbs.Any)
        {
            if (String.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException(nameof(path));
            }

            Path  = path;
            Verbs = verbs;
        }
예제 #11
0
        private object ServerBroadcast(RestVerbs verbs, IParameterCollection parameters)
        {
            var msg = parameters["msg"];

            if (string.IsNullOrWhiteSpace(msg))
            {
                return(RestMissingParam("msg"));
            }
            TShock.Utils.Broadcast(msg);
            return(RestResponse("The message was broadcasted successfully"));
        }
예제 #12
0
        private object ServerCommand(RestVerbs verbs, IParameterCollection parameters)
        {
            if (string.IsNullOrWhiteSpace(parameters["cmd"]))
            {
                return(RestMissingParam("cmd"));
            }

            TSRestPlayer tr = new TSRestPlayer();

            Commands.HandleCommand(tr, parameters["cmd"]);
            return(RestResponse(string.Join("\n", tr.GetCommandOutput())));
        }
예제 #13
0
        private object WorldChangeSaveSettings(RestVerbs verbs, IParameterCollection parameters)
        {
            bool autoSave;

            if (!bool.TryParse(verbs["bool"], out autoSave))
            {
                return(RestInvalidParam("state"));
            }
            TShock.Config.AutoSave = autoSave;

            return(RestResponse("AutoSave has been set to " + autoSave));
        }
예제 #14
0
        private object ServerStatus(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            var activeplayers = Main.player.Where(p => null != p && p.active).ToList();

            return(new RestObject()
            {
                { "name", TShock.Config.ServerName },
                { "port", Convert.ToString(Netplay.serverPort) },
                { "playercount", Convert.ToString(activeplayers.Count()) },
                { "players", string.Join(", ", activeplayers.Select(p => p.name)) },
            });
        }
예제 #15
0
        private object WorldBloodmoon(RestVerbs verbs, IParameterCollection parameters)
        {
            bool bloodmoon;

            if (!bool.TryParse(verbs["bool"], out bloodmoon))
            {
                return(RestInvalidParam("bloodmoon"));
            }
            Main.bloodMoon = bloodmoon;

            return(RestResponse("Blood Moon has been set to " + bloodmoon));
        }
예제 #16
0
 private object UserListV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     return(new RestObject()
     {
         { "users", TShock.Users.GetUsers().Select(p => new Dictionary <string, object>()
             {
                 { "name", p.Name },
                 { "id", p.ID },
                 { "group", p.Group },
             }) }
     });
 }
예제 #17
0
 private object WorldRead(RestVerbs verbs, IParameterCollection parameters)
 {
     return(new RestObject()
     {
         { "name", Main.worldName },
         { "size", Main.maxTilesX + "*" + Main.maxTilesY },
         { "time", Main.time },
         { "daytime", Main.dayTime },
         { "bloodmoon", Main.bloodMoon },
         { "invasionsize", Main.invasionSize }
     });
 }
예제 #18
0
 private object UserListV2(RestVerbs verbs, IParameterCollection parameters)
 {
     return(new RestObject()
     {
         { "users", TPulse.Users.GetUsers().Select(p => new Dictionary <string, object>()
             {
                 { "name", p.Name },
                 { "id", p.ID },
                 { "group", p.Group },
                 { "ip", p.Address },
             }) }
     });
 }
예제 #19
0
        private object WorldRead(RestVerbs verbs, IParameterCollection parameters)
        {
            var returnBlock = new Dictionary <string, object>();

            returnBlock.Add("status", "200");
            returnBlock.Add("name", Main.worldName);
            returnBlock.Add("size", Main.maxTilesX + "*" + Main.maxTilesY);
            returnBlock.Add("time", Main.time);
            returnBlock.Add("daytime", Main.dayTime);
            returnBlock.Add("bloodmoon", Main.bloodMoon);
            returnBlock.Add("invasionsize", Main.invasionSize);
            return(returnBlock);
        }
예제 #20
0
 object DestroyToken(RestVerbs verbs, IParameterCollection parameters)
 {
     var token = verbs["token"];
     try
     {
         Tokens.Remove(token);
     }
     catch (Exception)
     {
         return new Dictionary<string, string> { { "status", "400" }, { "error", "The specified token queued for destruction failed to be deleted." } };
     }
     return new Dictionary<string, string> { { "status", "200" }, { "response", "Requested token was successfully destroyed." } };
 }
예제 #21
0
        private object BanDestroy(RestVerbs verbs, IParameterCollection parameters)
        {
            var returnBlock = new Dictionary <string, string>();

            var type = parameters["type"];

            if (type == null)
            {
                returnBlock.Add("Error", "Invalid Type");
                return(returnBlock);
            }

            var ban = new Ban();

            if (type == "ip")
            {
                ban = TShock.Bans.GetBanByIp(verbs["user"]);
            }
            else if (type == "name")
            {
                ban = TShock.Bans.GetBanByName(verbs["user"]);
            }
            else
            {
                returnBlock.Add("Error", "Invalid Type");
                return(returnBlock);
            }

            if (ban == null)
            {
                return(new Dictionary <string, string> {
                    { "status", "400" }, { "error", "The specified ban does not exist." }
                });
            }

            try
            {
                TShock.Bans.RemoveBan(ban.IP);
            }
            catch (Exception)
            {
                returnBlock.Add("status", "400");
                returnBlock.Add("error", "The specified ban was unable to be removed.");
                return(returnBlock);
            }
            returnBlock.Add("status", "200");
            returnBlock.Add("response", "Ban deleted successfully.");
            returnBlock.Add("deprecated", "This endpoint is deprecated. It will be fully removed from code in TShock 3.6.");
            return(returnBlock);
        }
예제 #22
0
        private object ServerStatusV2(RestVerbs verbs, IParameterCollection parameters)
        {
            if (TShock.Config.EnableTokenEndpointAuthentication)
            {
                return(RestError("Server settings require a token for this API call"));
            }

            var ret = new RestObject()
            {
                { "name", TShock.Config.ServerName },
                { "port", TShock.Config.ServerPort },
                { "playercount", Main.player.Where(p => null != p && p.active).Count() },
                { "maxplayers", TShock.Config.MaxSlots },
                { "world", Main.worldName }
            };

            if (GetBool(parameters["players"], false))
            {
                var players = new ArrayList();
                foreach (TSPlayer tsPlayer in TShock.Players.Where(p => null != p))
                {
                    var p = PlayerFilter(tsPlayer, parameters);
                    if (null != p)
                    {
                        players.Add(p);
                    }
                }
                ret.Add("players", players);
            }

            if (GetBool(parameters["rules"], false))
            {
                var rules = new Dictionary <string, object>();
                rules.Add("AutoSave", TShock.Config.AutoSave);
                rules.Add("DisableBuild", TShock.Config.DisableBuild);
                rules.Add("DisableClownBombs", TShock.Config.DisableClownBombs);
                rules.Add("DisableDungeonGuardian", TShock.Config.DisableDungeonGuardian);
                rules.Add("DisableInvisPvP", TShock.Config.DisableInvisPvP);
                rules.Add("DisableSnowBalls", TShock.Config.DisableSnowBalls);
                rules.Add("DisableTombstones", TShock.Config.DisableTombstones);
                rules.Add("EnableWhitelist", TShock.Config.EnableWhitelist);
                rules.Add("HardcoreOnly", TShock.Config.HardcoreOnly);
                rules.Add("PvPMode", TShock.Config.PvPMode);
                rules.Add("SpawnProtection", TShock.Config.SpawnProtection);
                rules.Add("SpawnProtectionRadius", TShock.Config.SpawnProtectionRadius);

                ret.Add("rules", rules);
            }
            return(ret);
        }
예제 #23
0
        /// <summary>
        /// Gets an <see cref="IEnumerable{T}"/> of the verb strings.
        /// </summary>
        /// <param name="verbs"><see cref="RestVerbs"/> to get an enumeration of.</param>
        /// <returns>The <see cref="IEnumerable{T}"/> of verb <see cref="string"/>s.</returns>
        public static IEnumerable <string> ToEnumerable(this RestVerbs verbs)
        {
            if (verbs == RestVerbs.Any)
            {
                return new[] { verbs.ToString().ToUpper() }
            }
            ;

            return(verbs
                   .ToString()
                   .ToUpper()
                   .Split(',')
                   .Select(x => x.Trim()));
        }
예제 #24
0
        private object ServerOff(RestVerbs verbs, IParameterCollection parameters)
        {
            if (!GetBool(parameters["confirm"], false))
            {
                return(RestInvalidParam("confirm"));
            }

            // Inform players the server is shutting down
            var msg = string.IsNullOrWhiteSpace(parameters["message"]) ? "Server is shutting down" : parameters["message"];

            TShock.Utils.StopServer(!GetBool(parameters["nosave"], false), msg);

            return(RestResponse("The server is shutting down"));
        }
예제 #25
0
        protected override object ExecuteCommand(RestCommand cmd, RestVerbs verbs, IParameterCollection parms)
        {
            if (cmd.RequiresToken)
            {
                var strtoken = parms["token"];
                if (strtoken == null)
                    return new Dictionary<string, string> { { "status", "401" }, { "error", "Not authorized. The specified API endpoint requires a token." } };

                object token;
                if (!Tokens.TryGetValue(strtoken, out token))
                    return new Dictionary<string, string> { { "status", "403" }, { "error", "Not authorized. The specified API endpoint requires a token, but the provided token was not valid." } };
            }
            return base.ExecuteCommand(cmd, verbs, parms);
        }
예제 #26
0
        private object ServerRules(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            string rulesFilePath = Path.Combine(TShock.SavePath, "rules.txt");

            if (!File.Exists(rulesFilePath))
            {
                return(this.RestError("The rules.txt was not found.", "500"));
            }

            return(new RestObject()
            {
                { "rules", File.ReadAllLines(rulesFilePath) }
            });
        }
예제 #27
0
        private object ServerRestart(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            if (!GetBool(parameters["confirm"], false))
            {
                return(RestInvalidParam("confirm"));
            }

            // Inform players the server is shutting down
            var reason = string.IsNullOrWhiteSpace(parameters["message"]) ? "Server is restarting" : parameters["message"];

            TShock.Utils.RestartServer(!GetBool(parameters["nosave"], false), reason);

            return(RestResponse("The server is shutting down and will attempt to restart"));
        }
예제 #28
0
        public void Ctor__AddsEntryForEachMethod()
        {
            const string    path          = SvcForMethods.MultiPath;
            const RestVerbs methods       = SvcForMethods.MultiMethod;
            var             routes        = methods.GetFlags().Select(m => new RouteAttribute(path, m)).ToList();
            var             expectedKeys  = routes.Select(r => Utils.GetRouteKey(r)).ToList();
            var             expectedRoute = new RouteAttribute(path, methods);

            var service = new RService(_options);

            service.Routes.Keys.Should().Contain(expectedKeys);
            service.Routes[expectedKeys[0]].Route.Should().Be(expectedRoute);
            service.Routes[expectedKeys[1]].Route.Should().Be(expectedRoute);
        }
예제 #29
0
        private object Broadcast(RestVerbs verbs, IParameterCollection parameters)
        {
            if (parameters["msg"] != null && parameters["msg"].Trim() != "")
            {
                TShock.Utils.Broadcast(parameters["msg"]);
                RestObject reply = new RestObject("200");
                reply["response"] = "The message was broadcasted successfully.";
                return(reply);
            }
            RestObject fail = new RestObject("400");

            fail["response"] = "Broadcast failed.";
            return(fail);
        }
예제 #30
0
        private object PlayerKickV2(RestVerbs verbs, IParameterCollection parameters)
        {
            var ret = PlayerFind(parameters);

            if (ret is RestObject)
            {
                return(ret);
            }

            TSPlayer player = (TSPlayer)ret;

            TShock.Utils.ForceKick(player, null == parameters["reason"] ? "Kicked via web" : parameters["reason"], false, true);
            return(RestResponse("Player " + player.Name + " was kicked"));
        }
        private object GetInventory(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            List<TSPlayer> players = TShock.Utils.FindPlayer(verbs["user"]);
            if (players.Count > 1)
            {
                return new RestObject("400") {Response = "Found more than one match."};
            }
            else if (players.Count < 1)
            {
                return new RestObject("400") {Response = "Found no matches."};
            }

            string inventory = players[0].PlayerData.inventory.ToString();
            return new RestObject{{"inventory", inventory}};
        }
예제 #32
0
        private object GroupList(RestVerbs verbs, IParameterCollection parameters)
        {
            var groups = new ArrayList();

            foreach (Group group in TShock.Groups)
            {
                groups.Add(new Dictionary <string, object> {
                    { "name", group.Name }, { "parent", group.ParentName }, { "chatcolor", group.ChatColor }
                });
            }
            return(new RestObject()
            {
                { "groups", groups }
            });
        }
예제 #33
0
        private object ServerStatusV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            var ret = new RestObject()
            {
                { "name", TShock.Config.ServerName },
                { "port", TShock.Config.ServerPort },
                { "playercount", Main.player.Where(p => null != p && p.active).Count() },
                { "maxplayers", TShock.Config.MaxSlots },
                { "world", Main.worldName },
                { "uptime", (DateTime.Now - System.Diagnostics.Process.GetCurrentProcess().StartTime).ToString(@"d'.'hh':'mm':'ss") },
                { "serverpassword", !string.IsNullOrEmpty(TShock.Config.ServerPassword) }
            };

            if (GetBool(parameters["players"], false))
            {
                var players = new ArrayList();
                foreach (TSPlayer tsPlayer in TShock.Players.Where(p => null != p))
                {
                    var p = PlayerFilter(tsPlayer, parameters);
                    if (null != p)
                    {
                        players.Add(p);
                    }
                }
                ret.Add("players", players);
            }

            if (GetBool(parameters["rules"], false))
            {
                var rules = new Dictionary <string, object>();
                rules.Add("AutoSave", TShock.Config.AutoSave);
                rules.Add("DisableBuild", TShock.Config.DisableBuild);
                rules.Add("DisableClownBombs", TShock.Config.DisableClownBombs);
                rules.Add("DisableDungeonGuardian", TShock.Config.DisableDungeonGuardian);
                rules.Add("DisableInvisPvP", TShock.Config.DisableInvisPvP);
                rules.Add("DisableSnowBalls", TShock.Config.DisableSnowBalls);
                rules.Add("DisableTombstones", TShock.Config.DisableTombstones);
                rules.Add("EnableWhitelist", TShock.Config.EnableWhitelist);
                rules.Add("HardcoreOnly", TShock.Config.HardcoreOnly);
                rules.Add("PvPMode", TShock.Config.PvPMode);
                rules.Add("SpawnProtection", TShock.Config.SpawnProtection);
                rules.Add("SpawnProtectionRadius", TShock.Config.SpawnProtectionRadius);
                rules.Add("ServerSideInventory", TShock.Config.ServerSideInventory);

                ret.Add("rules", rules);
            }
            return(ret);
        }
예제 #34
0
        private object UserUpdateV2(RestVerbs verbs, IParameterCollection parameters)
        {
            var ret = UserFind(parameters);

            if (ret is RestObject)
            {
                return(ret);
            }

            var password = parameters["password"];
            var group    = parameters["group"];

            if (string.IsNullOrWhiteSpace(group) && string.IsNullOrWhiteSpace(password))
            {
                return(RestMissingParam("group", "password"));
            }

            User user     = (User)ret;
            var  response = new RestObject();

            if (!string.IsNullOrWhiteSpace(password))
            {
                try
                {
                    TShock.Users.SetUserPassword(user, password);
                    response.Add("password-response", "Password updated successfully");
                }
                catch (Exception e)
                {
                    return(RestError("Failed to update user password (" + e.Message + ")"));
                }
            }

            if (!string.IsNullOrWhiteSpace(group))
            {
                try
                {
                    TShock.Users.SetUserGroup(user, group);
                    response.Add("group-response", "Group updated successfully");
                }
                catch (Exception e)
                {
                    return(RestError("Failed to update user group (" + e.Message + ")"));
                }
            }

            return(response);
        }
예제 #35
0
        private object PlayerBanV2(RestVerbs verbs, IParameterCollection parameters)
        {
            var ret = PlayerFind(parameters);

            if (ret is RestObject)
            {
                return(ret);
            }

            TSPlayer player = (TSPlayer)ret;
            var      reason = null == parameters["reason"] ? "Banned via web" : parameters["reason"];

            TShock.Bans.AddBan(player.IP, player.Name, reason);
            TShock.Utils.ForceKick(player, reason, false, true);
            return(RestResponse("Player " + player.Name + " was banned"));
        }
예제 #36
0
        object BanCreate(RestVerbs verbs, IParameterCollection parameters)
        {
            var returnBlock = new Dictionary<string, string>();
            var ip = parameters["ip"];
            var name = parameters["name"];
            var reason = parameters["reason"];

            if (ip == null && name == null)
            {
                returnBlock.Add("status", "400");
                returnBlock.Add("error", "Required parameters were missing from this API endpoint.");
                return returnBlock;
            }

            if (ip == null)
            {
                ip = "";
            }

            if (name == null)
            {
                name = "";
            }

            if (reason == null)
            {
                reason = "";
            }

            try
            {
                TShock.Bans.AddBan(ip, name, reason);
            }
            catch (Exception)
            {
                returnBlock.Add("status", "400");
                returnBlock.Add("error", "The specified ban was unable to be created.");
                return returnBlock;
            }
            returnBlock.Add("status", "200");
            returnBlock.Add("response", "Ban created successfully.");
            return returnBlock;
        }
예제 #37
0
 private object WorldRead(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     return new RestObject()
     {
         {"name", Main.worldName},
         {"size", Main.maxTilesX + "*" + Main.maxTilesY},
         {"time", Main.time},
         {"daytime", Main.dayTime},
         {"bloodmoon", Main.bloodMoon},
         {"invasionsize", Main.invasionSize}
     };
 }
예제 #38
0
        private object WorldChangeSaveSettings(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            bool autoSave;
            if (!bool.TryParse(verbs["bool"], out autoSave))
                return RestInvalidParam("state");
            TShock.Config.AutoSave = autoSave;

            return RestResponse("AutoSave has been set to " + autoSave);
        }
예제 #39
0
        private object WorldBloodmoon(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            bool bloodmoon;
            if (!bool.TryParse(verbs["bool"], out bloodmoon))
                return RestInvalidParam("bloodmoon");
            Main.bloodMoon = bloodmoon;

            return RestResponse("Blood Moon has been set to " + bloodmoon);
        }
예제 #40
0
 private object UserListV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     return new RestObject() { { "users", TShock.Users.GetUsers().Select(p => new Dictionary<string,object>(){
         {"name", p.Name},
         {"id", p.ID},
         {"group", p.Group},
     }) } };
 }
예제 #41
0
        private object UserDestroyV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            var ret = UserFind(parameters);
            if (ret is RestObject)
                return ret;

            try
            {
                TShock.Users.RemoveUser((User)ret);
            }
            catch (Exception e)
            {
                return RestError(e.Message);
            }

            return RestResponse("User deleted successfully");
        }
예제 #42
0
 private object UserActiveListV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     return new RestObject() { { "activeusers", string.Join("\t", TShock.Players.Where(p => null != p && null != p.UserAccountName && p.Active).Select(p => p.UserAccountName)) } };
 }
예제 #43
0
        private object ServerStatusV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            var ret = new RestObject()
            {
                {"name", TShock.Config.ServerName},
                {"port", TShock.Config.ServerPort},
                {"playercount", Main.player.Where(p => null != p && p.active).Count()},
                {"maxplayers", TShock.Config.MaxSlots},
                {"world", Main.worldName},
                {"uptime", (DateTime.Now - System.Diagnostics.Process.GetCurrentProcess().StartTime).ToString(@"d'.'hh':'mm':'ss")},
                {"serverpassword", !string.IsNullOrEmpty(TShock.Config.ServerPassword)}
            };

            if (GetBool(parameters["players"], false))
            {
                var players = new ArrayList();
                foreach (TSPlayer tsPlayer in TShock.Players.Where(p => null != p))
                {
                    var p = PlayerFilter(tsPlayer, parameters, ((tokenData.UserGroupName) != "" && TShock.Utils.GetGroup(tokenData.UserGroupName).HasPermission(RestPermissions.viewips)));
                    if (null != p)
                        players.Add(p);
                }
                ret.Add("players", players);
            }

            if (GetBool(parameters["rules"], false))
            {
                var rules = new Dictionary<string,object>();
                rules.Add("AutoSave", TShock.Config.AutoSave);
                rules.Add("DisableBuild", TShock.Config.DisableBuild);
                rules.Add("DisableClownBombs", TShock.Config.DisableClownBombs);
                rules.Add("DisableDungeonGuardian", TShock.Config.DisableDungeonGuardian);
                rules.Add("DisableInvisPvP", TShock.Config.DisableInvisPvP);
                rules.Add("DisableSnowBalls", TShock.Config.DisableSnowBalls);
                rules.Add("DisableTombstones", TShock.Config.DisableTombstones);
                rules.Add("EnableWhitelist", TShock.Config.EnableWhitelist);
                rules.Add("HardcoreOnly", TShock.Config.HardcoreOnly);
                rules.Add("PvPMode", TShock.Config.PvPMode);
                rules.Add("SpawnProtection", TShock.Config.SpawnProtection);
                rules.Add("SpawnProtectionRadius", TShock.Config.SpawnProtectionRadius);
                rules.Add("ServerSideInventory", TShock.Config.ServerSideCharacter);

                ret.Add("rules", rules);
            }
            return ret;
        }
예제 #44
0
 private object PlayerList(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     var activeplayers = Main.player.Where(p => null != p && p.active).ToList();
     return new RestObject() { { "players", string.Join(", ", activeplayers.Select(p => p.name)) } };
 }
예제 #45
0
 private object ServerStatus(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     var activeplayers = Main.player.Where(p => null != p && p.active).ToList();
     return new RestObject()
     {
         {"name", TShock.Config.ServerName},
         {"port", Convert.ToString(Netplay.serverPort)},
         {"playercount", Convert.ToString(activeplayers.Count())},
         {"players", string.Join(", ", activeplayers.Select(p => p.name))},
     };
 }
예제 #46
0
 private object PlayerListV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     var playerList = new ArrayList();
     foreach (TSPlayer tsPlayer in TShock.Players.Where(p => null != p))
     {
         var p = PlayerFilter(tsPlayer, parameters);
         if (null != p)
             playerList.Add(p);
     }
     return new RestObject() { { "players", playerList } };
 }
예제 #47
0
 private object ServerTokenTest(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     return new RestObject()
     {
         {"response", "Token is valid and was passed through correctly."},
         {"associateduser", tokenData.Username}
     };
 }
예제 #48
0
        private object PlayerReadV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            var ret = PlayerFind(parameters);
            if (ret is RestObject)
                return ret;

            TSPlayer player = (TSPlayer)ret;
            var activeItems = player.TPlayer.inventory.Where(p => p.active).ToList();
            return new RestObject()
            {
                {"nickname", player.Name},
                {"username", null == player.UserAccountName ? "" : player.UserAccountName},
                {"ip", player.IP},
                {"group", player.Group.Name},
                {"position", player.TileX + "," + player.TileY},
                {"inventory", string.Join(", ", activeItems.Select(p => (p.name + ":" + p.stack)))},
                {"buffs", string.Join(", ", player.TPlayer.buffType)}
            };
        }
예제 #49
0
        private object UserCreateV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            var username = parameters["user"];
            if (string.IsNullOrWhiteSpace(username))
                return RestMissingParam("user");

            var group = parameters["group"];
            if (string.IsNullOrWhiteSpace(group))
                group = TShock.Config.DefaultRegistrationGroupName;

            var password = parameters["password"];
            if (string.IsNullOrWhiteSpace(password))
                return RestMissingParam("password");

            // NOTE: ip can be blank
            User user = new User(username, password, "", group, "", "", "");
            try
            {
                TShock.Users.AddUser(user);
            }
            catch (Exception e)
            {
                return RestError(e.Message);
            }

            return RestResponse("User was successfully created");
        }
예제 #50
0
 private object PlayerUnMute(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     return PlayerSetMute(parameters, false);
 }
예제 #51
0
        private object UserInfoV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            var ret = UserFind(parameters);
            if (ret is RestObject)
                return ret;

            User user = (User)ret;
            return new RestObject() { { "group", user.Group }, { "id", user.ID.ToString() }, { "name", user.Name } };
        }
예제 #52
0
 private object ServerBroadcast(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     var msg = parameters["msg"];
     if (string.IsNullOrWhiteSpace(msg))
         return RestMissingParam("msg");
     TShock.Utils.Broadcast(msg);
     return RestResponse("The message was broadcasted successfully");
 }
예제 #53
0
        private object UserUpdateV2(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            var ret = UserFind(parameters);
            if (ret is RestObject)
                return ret;

            var password = parameters["password"];
            var group = parameters["group"];
            if (string.IsNullOrWhiteSpace(group) && string.IsNullOrWhiteSpace(password))
                return RestMissingParam("group", "password");

            User user = (User)ret;
            var response = new RestObject();
            if (!string.IsNullOrWhiteSpace(password))
            {
                try
                {
                    TShock.Users.SetUserPassword(user, password);
                    response.Add("password-response", "Password updated successfully");
                }
                catch (Exception e)
                {
                    return RestError("Failed to update user password (" + e.Message + ")");
                }
            }

            if (!string.IsNullOrWhiteSpace(group))
            {
                try
                {
                    TShock.Users.SetUserGroup(user, group);
                    response.Add("group-response", "Group updated successfully");
                }
                catch (Exception e)
                {
                    return RestError("Failed to update user group (" + e.Message + ")");
                }
            }

            return response;
        }
예제 #54
0
        private object ServerCommandV3(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            if (string.IsNullOrWhiteSpace(parameters["cmd"]))
                return RestMissingParam("cmd");

            Group restPlayerGroup;
            // TODO: Get rid of this when the old REST permission model is removed.
            if (TShock.Config.RestUseNewPermissionModel)
                restPlayerGroup = TShock.Groups.GetGroupByName(tokenData.UserGroupName);
            else
                restPlayerGroup = new SuperAdminGroup();

            TSRestPlayer tr = new TSRestPlayer(tokenData.Username, restPlayerGroup);
            Commands.HandleCommand(tr, parameters["cmd"]);
            return new RestObject()
            {
                {"response", tr.GetCommandOutput()}
            };
        }
예제 #55
0
        private object WorldButcher(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            bool killFriendly;
            if (!bool.TryParse(parameters["killfriendly"], out killFriendly))
                return RestInvalidParam("killfriendly");

            if (killFriendly)
                killFriendly = !killFriendly;

            int killcount = 0;
            for (int i = 0; i < Main.npc.Length; i++)
            {
                if (Main.npc[i].active && Main.npc[i].type != 0 && !Main.npc[i].townNPC && (!Main.npc[i].friendly || killFriendly))
                {
                    TSPlayer.Server.StrikeNPC(i, 99999, 90f, 1);
                    killcount++;
                }
            }

            return RestResponse(killcount + " NPCs have been killed");
        }
예제 #56
0
        private object ServerReload(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            TShock.Utils.Reload(new TSRestPlayer(tokenData.Username, TShock.Groups.GetGroupByName(tokenData.UserGroupName)));

            return RestResponse("Configuration, permissions, and regions reload complete. Some changes may require a server restart.");
        }
예제 #57
0
 private object WorldMeteor(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
 {
     if (null == WorldGen.genRand)
         WorldGen.genRand = new Random();
     WorldGen.dropMeteor();
     return RestResponse("Meteor has been spawned");
 }
예제 #58
0
        private object ServerRestart(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            if (!GetBool(parameters["confirm"], false))
                return RestInvalidParam("confirm");

            // Inform players the server is shutting down
            var reason = string.IsNullOrWhiteSpace(parameters["message"]) ? "Server is restarting" : parameters["message"];
            TShock.Utils.RestartServer(!GetBool(parameters["nosave"], false), reason);

            return RestResponse("The server is shutting down and will attempt to restart");
        }
예제 #59
0
        private object WorldSave(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            SaveManager.Instance.SaveWorld();

            return RestResponse("World saved");
        }
예제 #60
0
        private object ServerRules(RestVerbs verbs, IParameterCollection parameters, SecureRest.TokenData tokenData)
        {
            string rulesFilePath = Path.Combine(TShock.SavePath, "rules.txt");
            if (!File.Exists(rulesFilePath))
                return this.RestError("The rules.txt was not found.", "500");

            return new RestObject()
            {
                {"rules", File.ReadAllLines(rulesFilePath)}
            };
        }