Ejemplo n.º 1
0
        public static string BanUser(User user, int originID)
        {
            string IP = user.tcpClient.Client.RemoteEndPoint.ToString().Split(':')[0];

            MySql.Query("INSERT INTO bans (IP,From) VALUES(\'" + IP + "\'," + originID + ")");
            return(IP);
        }
Ejemplo n.º 2
0
        public static Hashtable AddSong(bool Start, User user)
        {
            if (user.CurrentRoom == null || user.CurrentRoom.CurrentSong == null || user.CurrentRoom.Reported)
            {
                return(null);
            }

            string Name     = MySql.AddSlashes(OpenSMO.User.Utf8Decode(user.CurrentRoom.CurrentSong.Name));
            string Artist   = MySql.AddSlashes(OpenSMO.User.Utf8Decode(user.CurrentRoom.CurrentSong.Artist));
            string SubTitle = MySql.AddSlashes(OpenSMO.User.Utf8Decode(user.CurrentRoom.CurrentSong.SubTitle));

            Hashtable song = Data.GetSong(Name, Artist, SubTitle);

            if (user.ShadowBanned)
            {
                if (song != null)
                {
                    return(song);
                }
                else
                {
                    Hashtable ret = new Hashtable();
                    ret["ID"]       = -1;
                    ret["Name"]     = Name;
                    ret["Artist"]   = Artist;
                    ret["SubTitle"] = SubTitle;
                    ret["Played"]   = 0;
                    ret["Notes"]    = 0;
                    return(ret);
                }
            }

            if (song == null)
            {
                MySql.Query("INSERT INTO songs (Name,Artist,SubTitle) VALUES(" +
                            "'" + Name + "'," +
                            "'" + Artist + "'," +
                            "'" + SubTitle + "')");

                return(MySql.Query("SELECT * FROM songs ORDER BY 'ID' DESC LIMIT 0,1")[0]);
            }
            else if (Start)
            {
                MySql.Query("UPDATE songs SET Played=Played+1 WHERE ID=" + song["ID"].ToString());
                user.CurrentRoom.Reported = true;
            }

            return(song);
        }
Ejemplo n.º 3
0
 public static int CreateRoomDB(User user)
 {
     if (user.CurrentRoom == null || user.CurrentRoom.CurrentSong == null)
     {
         return(-1);
     }
     else
     {
         string owner = MySql.AddSlashes(user.CurrentRoom.Owner.User_Name);
         string name  = MySql.AddSlashes(user.CurrentRoom.Name);
         string desc  = MySql.AddSlashes(user.CurrentRoom.Description);
         MySql.Query("INSERT INTO rooms (Name,Description,Owner) VALUES('" + name + "','" + desc + "','" + owner + "')");
         MainClass.AddLog("Owner: " + owner + " Name: " + name + "Description: " + desc);
         Hashtable[] getroomid  = MySql.Query("SELECT ID from rooms where Name = '" + name + "' and Description = '" + desc + "' and Owner = '" + owner + "' ORDER BY created DESC LIMIT 1");
         Hashtable   roomidhash = getroomid[0];
         int         roomid     = (int)roomidhash["ID"];
         return(roomid);
     }
 }
Ejemplo n.º 4
0
        public static Hashtable GetSong(string Name, string Artist, string SubTitle)
        {
            Hashtable[] resCheck = MySql.Query("SELECT * FROM songs WHERE Name='" + Name + "' " +
                                               "AND Artist='" + Artist + "' " +
                                               "AND SubTitle='" + SubTitle + "'");

            if (resCheck == null)
            {
                return(null);
            }
            if (resCheck.Length == 1)
            {
                return(resCheck[0]);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 5
0
        public static Hashtable GetSong(string Name, string Artist, string SubTitle)
        {
            Hashtable[] resCheck = MySql.Query("SELECT * FROM songs WHERE BINARY Name='" + Name + "' " +
                                               "AND BINARY Artist='" + Artist + "' " +
                                               "AND BINARY SubTitle='" + SubTitle + "' LIMIT 1");

            MainClass.AddLog("A DB select was made on (Name,Artist,Subtitle) VALUES('" + Name + "','" + Artist + "','" + SubTitle + "')");
            if (resCheck == null)
            {
                return(null);
            }
            if (resCheck.Length == 1)
            {
                return(resCheck[0]);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 6
0
 public static Hashtable SongPlayed(int ID)
 {
     Hashtable[] resCheck = MySql.Query("SELECT  count(*) AS 'Played' from stats where song ='" + ID + "'");
     return(resCheck[0]);
 }
Ejemplo n.º 7
0
        public static void AddStats(User user)
        {
            if (user.CurrentRoom == null)
            {
                return;
            }

            if (user.CurrentRoom.CurrentSong == null)
            {
                return;
            }

            string Name     = MySql.AddSlashes(OpenSMO.User.Utf8Decode(user.CurrentRoom.CurrentSong.Name));
            string Artist   = MySql.AddSlashes(OpenSMO.User.Utf8Decode(user.CurrentRoom.CurrentSong.Artist));
            string SubTitle = MySql.AddSlashes(OpenSMO.User.Utf8Decode(user.CurrentRoom.CurrentSong.SubTitle));

            int       songID = 0;
            Hashtable song   = Data.GetSong(Name, Artist, SubTitle);

            if (song == null)
            {
                MySql.Query("INSERT INTO songs (Name,Artist,SubTitle) VALUES(" +
                            "'" + Name + "'," +
                            "'" + Artist + "'," +
                            "'" + SubTitle + "')");
            }
            Hashtable newsong = Data.GetSong(Name, Artist, SubTitle);


            if (newsong != null)
            {
                if (!user.ShadowBanned)
                {
                    double songTime = user.SongTime.Elapsed.TotalSeconds;
                    if (songTime != 0)
                    {
                        if ((user.SongOptions.Contains("Fail")) && (user.User_Protocol == 2))
                        {
//                        if (songTime > (int)newsong["Time"])
//            {
                            MySql.Query("UPDATE songs SET Time=" + songTime.ToString().Replace(',', '.') + " WHERE ID=" + newsong["ID"]);
                        }
//      }
                    }
                }
            }



//    MainClass.AddLog("User ID  " +user.User_Table["ID"].ToString()  + "'s Final Timing: " + user.timing);
            MainClass.AddLog("User ID  " + user.User_Table["ID"].ToString() + "'s Toasty Count: " + user.toasty);
            MainClass.AddLog("User ID  " + user.User_Table["ID"].ToString() + "'s Room ID: " + user.CurrentRoom.roomid);
            // Give player XP
            int XP = 0;

            for (int i = 3; i <= 8; i++)
            {
                XP += (i - 3) * user.Notes[i];
            }
//
            MainClass.AddLog("Regular XP: " + XP + "Jump XP: " + user.jumpxp);
            XP         += user.jumpxp;
            user.jumpxp = 0;
            XP         /= 6;
            if (user.timing > 2)
            {
                user.toasty = 0;
                XP          = 0;
            }
//            user.SendChatMessage("You gained " + Func.ChatColor("aaaa00") + XP.ToString() + Func.ChatColor("ffffff") + " XP!");
            int toastyxp = (user.toasty * 50);

            XP += toastyxp;

//    user.SendChatMessage("You gained an additional " + Func.ChatColor("aaaa00") + toastyxp.ToString() + Func.ChatColor("ffffff") + " Bonus XP for " + user.toasty + " Toasty(s) for a total of " + Func.ChatColor("aaaa00") + XP.ToString() + Func.ChatColor("ffffff") + " XP!");

            int fullcomboxp = 0;
            int marv        = user.Notes[8];
            int perf        = user.Notes[7];
            int grea        = user.Notes[6];
            int good        = user.Notes[5];
            int boo         = user.Notes[4];
            int miss        = user.Notes[3];
            int ok          = user.Notes[10];
            int ng          = user.Notes[9];

            float  Tpnt     = (3 * marv) + (2 * perf) + grea - (4 * boo) - (8 * miss) + (6 * ok);
            float  Tmaxpnt  = 3 * (marv + perf + grea + good + boo + miss) + 6 * (ok + ng);
            float  percentf = (Tpnt / Tmaxpnt) * 100F;
            string mpercent = percentf.ToString("n3");
            string percent  = percentf.ToString("n2");

            if ((miss == 0) && (boo == 0) && (good == 0) && ((marv + perf + grea) > 8))
            {
                if ((marv + perf + grea) > 150)
                {
                    fullcomboxp = 100;
                }
            }

            XP += fullcomboxp;
            int pretoastyxp = XP;


            string percentageq = "round(100.00/(3 * (Note_Flawless + Note_Perfect + Note_Great + Note_Good + Note_Barely + Note_Miss) + 6 * (Note_Held + Note_NG))*((3 * Note_Flawless) + (2 * Note_Perfect) + Note_Great - (4 * Note_Barely) - (8 * Note_Miss) + (6 * Note_Held)),3)";

            if (newsong != null)
            {
                songID = (int)newsong["ID"];

                Hashtable[] smoPBestQuery = MySql.Query("select count(*) as 'count' from stats where song = " + songID.ToString() + " and user = "******"ID"].ToString() + " and Difficulty = '" + ((int)user.GameDifficulty).ToString() + "' and Feet = '" + user.GameFeet.ToString() + "'  and " + percentageq + " > '" + mpercent + "'");
                Hashtable   PBStats       = smoPBestQuery[0];
                int         count         = (int)PBStats["count"];
                count += 1;

                Hashtable[] smoPBestTotalQuery = MySql.Query("select count(*) as 'count' from stats where song = " + songID.ToString() + " and user = "******"ID"].ToString() + " and Difficulty = '" + ((int)user.GameDifficulty).ToString() + "' and Feet = '" + user.GameFeet.ToString() + "'");
                Hashtable   oPBStats           = smoPBestTotalQuery[0];
                int         ocount             = (int)oPBStats["count"];
                ocount += 1;

                Hashtable[] smoTBestQuery = MySql.Query("select count(*) as 'count' from stats where song = " + songID.ToString() + " and Difficulty = '" + ((int)user.GameDifficulty).ToString() + "' and Feet = '" + user.GameFeet.ToString() + "'  and " + percentageq + " > '" + mpercent + "'");
                Hashtable   TBStats       = smoTBestQuery[0];
                int         tcount        = (int)TBStats["count"];
                tcount += 1;

                Hashtable[] smoTBestTotalQuery = MySql.Query("select count(*) as 'count' from stats where song = " + songID.ToString() + " and Difficulty = '" + ((int)user.GameDifficulty).ToString() + "' and Feet = '" + user.GameFeet.ToString() + "'");
                Hashtable   oTBStats           = smoTBestTotalQuery[0];
                int         tocount            = (int)oTBStats["count"];
                tocount += 1;
                string bestmessage = Func.ChatColor("aaaa00") + percent + "%" + Func.ChatColor("ffffff") + " PB: #" + Func.ChatColor("aaaa00") + count + "/" + ocount + Func.ChatColor("ffffff") + " TB: #" + Func.ChatColor("aaaa00") + tcount + "/" + tocount + Func.ChatColor("ffffff");
                if (user.toasty > 0)
                {
                    bestmessage = bestmessage + " " + Func.ChatColor("aaaa00") + pretoastyxp + "+" + toastyxp + Func.ChatColor("ffffff") + " XP Gained  - " + Func.ChatColor("aaaa00") + user.toasty + Func.ChatColor("ffffff") + " Toasty(s)";
                }
                else
                {
                    bestmessage = bestmessage + " " + Func.ChatColor("aaaa00") + pretoastyxp + Func.ChatColor("ffffff") + " XP Gained ";
                }

                if (fullcomboxp > 0)
                {
                    bestmessage = bestmessage + " -FC";
                }
                fullcomboxp = 0;

                if (user.timing > 2)
                {
                    bestmessage = bestmessage + " -TIMING";
                }

                if (user.ShowOffset)
                {
                    double clientoffsetavg = user.clientoffset / (double)user.clientoffsetcount;
                    double clientoffsetms  = clientoffsetavg * (double)1000;

                    bestmessage = bestmessage + " " + Func.ChatColor("aa0000") + "+" + user.offsetpos.ToString() + Func.ChatColor("ffffff") + "/" + Func.ChatColor("aa0000") + "-" + user.offsetneg.ToString() + " " + clientoffsetms.ToString("n3") + Func.ChatColor("ffffff") + "ms";
                }


                string playerSettings = Sql.AddSlashes(user.GamePlayerSettings);

                if (!user.ShadowBanned)
                {
                    // Big-ass query right there...
                    if (!user.ShadowBanned)
                    {
                        MySql.Query("INSERT INTO stats (User,PlayerSettings,Song,Room,Feet,Difficulty,Grade,Score,MaxCombo," +
                                    "Note_0,Note_1,Note_Mine,Note_Miss,Note_Barely,Note_Good,Note_Great,Note_Perfect,Note_Flawless,Note_NG,Note_Held,Toasty,timing, rate) VALUES(" +
                                    user.User_Table["ID"].ToString() + ",'" + playerSettings + "'," + songID.ToString() + "," + user.CurrentRoom.roomid.ToString() + "," + user.GameFeet.ToString() + "," + ((int)user.GameDifficulty).ToString() + "," + ((int)user.Grade).ToString() + "," + user.Score.ToString() + "," + user.MaxCombo.ToString() + "," +
                                    user.Notes[0].ToString() + "," + user.Notes[1].ToString() + "," + user.Notes[2].ToString() + "," + user.Notes[3].ToString() + "," + user.Notes[4].ToString() + "," + user.Notes[5].ToString() + "," + user.Notes[6].ToString() + "," + user.Notes[7].ToString() + "," + user.Notes[8].ToString() + "," + user.Notes[9].ToString() + "," + user.Notes[10].ToString() + "," + user.toasty + "," + user.timing + "," + user.PlayerRate + ")");
                    }
                }



                user.SendRoomChatMessage(bestmessage);

                user.toasty            = 0;
                user.timing            = 0;
                user.offsetneg         = 0;
                user.offsetpos         = 0;
                user.clientoffsetcount = 0;
                user.clientoffset      = 0;
                user.servcombo         = 0;
                user.perfmarv          = 0;
            }
            if (!user.ShadowBanned)
            {
                MySql.Query("UPDATE users SET XP=XP+" + XP.ToString() + " WHERE ID=" + user.User_ID.ToString());
            }

            //Update Current rank in users name
            Hashtable[] checkxp   = MySql.Query("select XP from users where ID = '" + user.User_Table["ID"].ToString() + "'");
            Hashtable   XP_Table  = checkxp[0];
            int         currentxp = (int)XP_Table["XP"] + 1;

            Hashtable[] checkrank      = MySql.Query("select count(*) as 'levelrank' from users where xp > '" + currentxp.ToString() + "'");
            Hashtable   New_Rank_Table = checkrank[0];
            int         oldrank        = user.User_Level_Rank;

            user.User_Level_Rank = (int)New_Rank_Table["levelrank"] + 1;
            if (oldrank != user.User_Level_Rank)
            {
                user.SendChatMessage("Your Rank changed from " + Func.ChatColor("aaaa00") + oldrank.ToString() + Func.ChatColor("ffffff") + " to " + Func.ChatColor("aaaa00") + user.User_Level_Rank.ToString() + Func.ChatColor("ffffff") + " -- Congratz!");
            }
        }
Ejemplo n.º 8
0
 public static bool IsBanned(string IP)
 {
     Hashtable[] res = MySql.Query("SELECT * FROM bans WHERE IP = \'" + MySql.AddSlashes(IP) + "\'");
     return(res.Length != 0);
 }
Ejemplo n.º 9
0
        public MainClass(string[] args)
        {
            Instance  = this;
            StartTime = DateTime.Now;

            string argConfigFile = "Config.ini";

            try {
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "--help":
                    case "-h":
                    case "-?":
                    default:
                        this.ShowHelp();
                        return;

                    case "--version":
                    case "-v":
                        Console.WriteLine("OpenSMO build " + Build);
                        return;

                    case "--config":
                    case "-c":
                        argConfigFile = args[++i];
                        break;
                    }
                }
            } catch {
                this.ShowHelp();
            }

            ServerConfig = new Config(argConfigFile);

            Console.Title = ServerConfig.Get("Server_Name");

            AddLog("Server starting at " + StartTime);

            if (bool.Parse(ServerConfig.Get("Server_HigherPriority")))
            {
                AddLog("Setting priority to above normal");
                Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
            }

            FPS = int.Parse(ServerConfig.Get("Server_FPS"));

            // Get optional advanced settings
            if (ServerConfig.Contains("Server_Offset"))
            {
                ServerOffset = (byte)int.Parse(ServerConfig.Get("Server_Offset"));
            }
            if (ServerConfig.Contains("Server_Version"))
            {
                ServerVersion = (byte)int.Parse(ServerConfig.Get("Server_Version"));
            }
            if (ServerConfig.Contains("Server_MaxPlayers"))
            {
                ServerMaxPlayers = (byte)int.Parse(ServerConfig.Get("Server_MaxPlayers"));
            }

            MySql.Host     = ServerConfig.Get("MySql_Host");
            MySql.User     = ServerConfig.Get("MySql_User");
            MySql.Password = ServerConfig.Get("MySql_Password");
            MySql.Database = ServerConfig.Get("MySql_Database");


            Hashtable[] fixedRooms = MySql.Query("SELECT * FROM fixedrooms;");

            if (fixedRooms == null)
            {
                AddLog("It appears there's no \"fixedrooms\" table, creating one now.");
                MySql.Query(@"CREATE TABLE ""main"".""fixedrooms"" (
          ""ID""  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
          ""Name""  TEXT(255) NOT NULL,
          ""Description""  TEXT(255),
          ""Password""  TEXT(255),
          ""Free""  INTEGER,
          ""MOTD""  TEXT(255),
          ""Operators""  TEXT(255));");
            }
            else
            {
                foreach (Hashtable room in fixedRooms)
                {
                    Room newRoom = new Room(this, null);
                    newRoom.Fixed       = true;
                    newRoom.Name        = room["Name"].ToString();
                    newRoom.Description = room["Description"].ToString();
                    newRoom.Password    = room["Password"].ToString();
                    newRoom.Free        = room["Free"].ToString() == "1";
                    newRoom.FixedMotd   = room["MOTD"].ToString();

                    string[]   strOps = room["Operators"].ToString().Split(',');
                    List <int> ops    = new List <int>();
                    foreach (string op in strOps)
                    {
                        if (op == "")
                        {
                            continue;
                        }

                        int opID = 0;
                        if (int.TryParse(op, out opID))
                        {
                            ops.Add(opID);
                        }
                        else
                        {
                            AddLog("Invalid op ID '" + op + "'");
                        }
                    }
                    newRoom.FixedOperators = ops.ToArray();
                    Rooms.Add(newRoom);

                    AddLog("Added fixed room '" + newRoom.Name + "'");
                }
            }

            ReloadScripts();

            tcpListener = new TcpListener(IPAddress.Parse(ServerConfig.Get("Server_IP")), int.Parse(ServerConfig.Get("Server_Port")));
            tcpListener.Start();

            AddLog("Server started on port " + ServerConfig.Get("Server_Port"));

            new Thread(new ThreadStart(UserThread)).Start();

            if (bool.Parse(ServerConfig.Get("RTS_Enabled")))
            {
                tcpListenerRTS = new TcpListener(IPAddress.Parse(ServerConfig.Get("RTS_IP")), int.Parse(ServerConfig.Get("RTS_Port")));
                tcpListenerRTS.Start();

                AddLog("RTS server started on port " + ServerConfig.Get("RTS_Port"));

                new Thread(new ThreadStart(RTSThread)).Start();
            }

            AddLog("Server running.");

            while (true)
            {
                TcpClient newTcpClient = tcpListener.AcceptTcpClient();

                string IP = newTcpClient.Client.RemoteEndPoint.ToString().Split(':')[0];
                if (Data.IsBanned(IP))
                {
                    if (bool.Parse(ServerConfig.Get("Game_ShadowBan")))
                    {
                        AddLog("Shadowbanned client connected: " + IP, true);

                        User newUser = new User(this, newTcpClient);
                        newUser.ShadowBanned = true;
                        Users.Add(newUser);
                    }
                    else
                    {
                        AddLog("Banned client kicked: " + IP, true);
                        newTcpClient.Close();
                    }
                }
                else
                {
                    AddLog("Client connected: " + IP);

                    User newUser = new User(this, newTcpClient);
                    Users.Add(newUser);
                }
            }
        }
Ejemplo n.º 10
0
        public void RTSThread()
        {
            while (true)
            {
                TcpClient newClient = tcpListenerRTS.AcceptTcpClient();

                new Thread(new ThreadStart(delegate
                {
                    TcpClient newTcpClient = newClient;
                    string IP = newTcpClient.Client.RemoteEndPoint.ToString().Split(':')[0];

                    NetworkStream stream = newTcpClient.GetStream();
                    StreamReader reader  = new StreamReader(stream);
                    StreamWriter writer  = new StreamWriter(stream)
                    {
                        AutoFlush = true
                    };

                    try {
                        string line = reader.ReadLine();

                        while (reader.ReadLine() != "")
                        {
                        }

                        if (line != null)
                        {
                            string[] requestParts = line.Split(' ')[1].Substring(1).Split(new char[] { '?' }, 2);
                            string request        = requestParts[0];
                            string data           = requestParts.Length == 2 ? Uri.UnescapeDataString(requestParts[1]).Replace('+', ' ') : "";
                            string[] parse        = request.Split('/');

                            string roomID = "";
                            Room r        = null;

                            string responseBuffer = "";
                            switch (parse[0])
                            {
                            case "l":
                                if (IP != ServerConfig.Get("RTS_Trusted"))
                                {
                                    responseBuffer = "[]";
                                    break;
                                }

                                responseBuffer = "[";
                                foreach (Room room in Rooms)
                                {
                                    if (!room.Secret && (room.Owner != null && !room.Owner.ShadowBanned))
                                    {
                                        responseBuffer += "[";
                                        responseBuffer += "\"" + room.ID + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.Name) + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.Description) + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.Owner.User_Name) + "\",";
                                        responseBuffer += room.Users.Count + ",";
                                        responseBuffer += "\"" + room.Status.ToString() + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.CurrentSong.Name) + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.CurrentSong.Artist) + "\"";
                                        responseBuffer += "]";

                                        if (Rooms.Last() != room)
                                        {
                                            responseBuffer += ",";
                                        }
                                    }
                                }
                                responseBuffer += "]";
                                break;

                            case "g":
                                roomID = parse[1];
                                r      = null;
                                foreach (Room room in Rooms)
                                {
                                    if (room.ID == roomID)
                                    {
                                        r = room;
                                        break;
                                    }
                                }

                                if (r == null || r.Secret)
                                {
                                    responseBuffer = "[]";
                                }
                                else
                                {
                                    User[] usersOrig = r.Users.ToArray();
                                    if (usersOrig.Length == 0)
                                    {
                                        responseBuffer = "[]";
                                    }
                                    else
                                    {
                                        User[] users    = (from user in usersOrig orderby user.SMOScore descending select user).ToArray();
                                        responseBuffer += "[[\"" + JsonSafe(r.Name) + "\",";
                                        responseBuffer += "\"" + JsonSafe(r.Description) + "\",";
                                        responseBuffer += "\"" + JsonSafe(r.CurrentSong.Artist + " - " + r.CurrentSong.Name) + "\",";
                                        if (r.CurrentSong.Time == 0)
                                        {
                                            responseBuffer += "false,";
                                        }
                                        else
                                        {
                                            responseBuffer += "\"" + (int)Math.Min(100, Math.Floor(100d / r.CurrentSong.Time * usersOrig[0].SongTime.ElapsedMilliseconds / 1000d)) + "%\",";
                                        }
                                        responseBuffer += "\"" + JsonSafe(r.ChatBuffer) + "\"";
                                        responseBuffer += "],";
                                        foreach (User user in users)
                                        {
                                            responseBuffer += "[";
                                            responseBuffer += user.User_ID + ",";
                                            responseBuffer += "\"" + JsonSafe(user.User_Name) + "\",";
                                            responseBuffer += "\"" + user.Combo + " / " + user.MaxCombo + "\",";
                                            responseBuffer += user.SMOScore + ",";
                                            responseBuffer += "\"" + user.Grade + "\",";
                                            responseBuffer += "\"" + user.GameDifficulty + "\",";
                                            responseBuffer += "\"" + JsonSafe(user.GamePlayerSettings) + "\"";
                                            responseBuffer += "],";
                                        }
                                        responseBuffer += "]";
                                    }
                                }
                                break;

                            case "c":
                                if (IP != ServerConfig.Get("RTS_Trusted"))
                                {
                                    responseBuffer = "[]";
                                    break;
                                }

                                roomID = parse[1];

                                Hashtable[] userRes = MySql.Query("SELECT * FROM users WHERE Username='******'");
                                if (userRes.Length != 1)
                                {
                                    break;
                                }

                                Hashtable u = userRes[0];

                                r = null;
                                foreach (Room room in Rooms)
                                {
                                    if (room.ID == roomID)
                                    {
                                        r = room;
                                        break;
                                    }
                                }

                                if (r != null && !r.Secret)
                                {
                                    string strName = u["Username"].ToString();

                                    for (int i = 0; i < Scripting.WebFormatHooks.Count; i++)
                                    {
                                        strName = Scripting.WebFormatHooks[i](u, strName);
                                    }

                                    SendChatAll(strName + ": " + data, r);
                                }

                                responseBuffer = "OK";
                                break;
                            }

                            writer.WriteLine("HTTP/1.1 200 OK");
                            writer.WriteLine("Content-Type: text/plain");
                            writer.WriteLine("access-control-allow-origin: *");
                            writer.WriteLine("access-control-allow-credentials: true");
                            writer.WriteLine("Content-Length: " + responseBuffer.Length);
                            writer.WriteLine("Connection: close");
                            writer.WriteLine();
                            writer.Write(responseBuffer);
                        }
                    } catch (Exception ex) {
                        AddLog("RTS request encountered '" + ex.GetType().Name + "' from " + IP, true);
                    }

                    stream.Close();
                    stream.Dispose();
                })).Start();
            }
        }
Ejemplo n.º 11
0
        // Client sent SMO packet (note subpacket comments)
        public void NSCSMOnline()
        {
            packetCommandSub = ez.Read1();
            byte packetCommandSubSub = ez.Read1();

            if (packetCommandSub == 0) // Login
            {
                ez.Read1();            // Reserved byte

                string smoUsername = ez.ReadNT();
                string smoPassword = ez.ReadNT();

                if (!new Regex("^([A-F0-9]{32})$").Match(smoPassword).Success)
                {
                    ez.Write1((byte)(mainClass.ServerOffset + NSCommand.NSCSMOnline));
                    ez.Write2(1);
                    ez.WriteNT("Login failed! Invalid password.");
                    ez.SendPack();

                    MainClass.AddLog("Invalid password hash given!", true);
                    return;
                }

                Hashtable[] smoLoginCheck = MySql.Query("SELECT * FROM users WHERE Username='******'");
                if (smoLoginCheck.Length == 1 && smoLoginCheck[0]["Password"].ToString() == smoPassword)
                {
                    MainClass.AddLog(smoUsername + " logged in.");

                    User_Table = smoLoginCheck[0];
                    User_ID    = (int)User_Table["ID"];
                    User_Name  = (string)User_Table["Username"];
                    User_Rank  = (UserRank)User_Table["Rank"];

                    ez.Write1((byte)(mainClass.ServerOffset + NSCommand.NSCSMOnline));
                    ez.Write2(0);
                    ez.WriteNT("Login success!");
                    ez.SendPack();

                    SendChatMessage(mainClass.ServerConfig.Get("Server_MOTD"));
                    SendRoomList();

                    User[] users = GetUsersInRoom();
                    foreach (User user in users)
                    {
                        user.SendRoomPlayers();
                    }

                    return;
                }
                else if (smoLoginCheck.Length == 0)
                {
                    if (bool.Parse(mainClass.ServerConfig.Get("Allow_Registration")))
                    {
                        smoUsername = smoUsername.Trim();

                        if (smoUsername.Trim() == "")
                        {
                            ez.Write1((byte)(mainClass.ServerOffset + NSCommand.NSCSMOnline));
                            ez.Write2(1);
                            ez.WriteNT("Registration failed! Invalid username.");
                            ez.SendPack();
                            return;
                        }

                        MySql.Query("INSERT INTO users (Username,Password,Email,Rank,XP) VALUES(\"" + MySql.AddSlashes(smoUsername) + "\",\"" + MySql.AddSlashes(smoPassword) + "\",\"\",0,0)");
                        MainClass.AddLog(smoUsername + " is now registered");

                        User_Table = MySql.Query("SELECT * FROM users WHERE Username='******' AND Password='******'")[0];
                        User_ID    = (int)User_Table["ID"];
                        User_Name  = (string)User_Table["Username"];
                        User_Rank  = (UserRank)User_Table["Rank"];

                        ez.Write1((byte)(mainClass.ServerOffset + NSCommand.NSCSMOnline));
                        ez.Write2(0);
                        ez.WriteNT("Login success!");
                        ez.SendPack();

                        SendChatMessage(mainClass.ServerConfig.Get("Server_MOTD"));
                        SendRoomList();

                        User[] users = GetUsersInRoom();
                        foreach (User user in users)
                        {
                            user.SendRoomPlayers();
                        }

                        return;
                    }
                }

                MainClass.AddLog(smoUsername + " tried logging in but failed");

                ez.Write1((byte)(mainClass.ServerOffset + NSCommand.NSCSMOnline));
                ez.Write2(1);
                ez.WriteNT("Login failed! Invalid password.");
                ez.SendPack();
            }
            else if (packetCommandSub == 01) // Join room
            {
                if (!RequiresAuthentication())
                {
                    return;
                }

                if (ez.LastPacketSize == 0)
                {
                    return;
                }

                string joinRoomName = ez.ReadNT();
                string joinRoomPass = "";

                if (ez.LastPacketSize > 0)
                {
                    joinRoomPass = ez.ReadNT();
                }

                foreach (Room room in mainClass.Rooms)
                {
                    if (room.Name == joinRoomName && (room.Password == joinRoomPass || IsModerator()))
                    {
                        CurrentRoomRights = RoomRights.Player;
                        CurrentRoom       = room;
                        SendToRoom();
                        break;
                    }
                }
            }
            else if (packetCommandSub == 02) // New room
            {
                if (!RequiresAuthentication())
                {
                    return;
                }

                string newRoomName = ez.ReadNT();
                string newRoomDesc = ez.ReadNT();
                string newRoomPass = "";

                if (ez.LastPacketSize > 0)
                {
                    newRoomPass = ez.ReadNT();
                }

                MainClass.AddLog(User_Name + " made a new room '" + newRoomName + "'");

                Room newRoom = new Room(mainClass, this);

                newRoom.Name        = newRoomName;
                newRoom.Description = newRoomDesc;
                newRoom.Password    = newRoomPass;

                mainClass.Rooms.Add(newRoom);

                User[] users = GetUsersInRoom();
                foreach (User user in users)
                {
                    user.SendRoomList();
                }

                CurrentRoom       = newRoom;
                CurrentRoomRights = RoomRights.Owner;
                SendToRoom();

                SendChatMessage("Welcome to your room! Type /help for a list of commands.");
            }
            else
            {
                // This is probably only for command sub 3, which is information you get when you hover over a room in the lobby.
                // TODO: Make NSCSMOnline sub packet 3 (room info on hover)
                //MainClass.AddLog( "Discarded unknown sub-packet " + packetCommandSub.ToString() + " for NSCSMOnline" );
                ez.Discard();
            }
        }
Ejemplo n.º 12
0
        public void RTSThread()
        {
            while (true)
            {
                TcpClient newClient = tcpListenerRTS.AcceptTcpClient();

                new Thread(new ThreadStart(delegate
                {
                    string IP = "";
                    TcpClient newTcpClient = newClient;
                    try
                    {
                        IP = newTcpClient.Client.RemoteEndPoint.ToString().Split(':')[0];
                    }
                    catch (SocketException e)
                    {
                        AddLog("RTS Exception: Disconnected: error code: " + e.NativeErrorCode.ToString());
                    }

                    NetworkStream stream = newTcpClient.GetStream();
                    stream.ReadTimeout   = 500;
                    stream.WriteTimeout  = 500;
                    StreamReader reader  = new StreamReader(stream);
                    StreamWriter writer  = new StreamWriter(stream)
                    {
                        AutoFlush = true
                    };

                    try
                    {
                        string line = reader.ReadLine();
                        if (line != null)
                        {
                            string[] requestParts = line.Split(' ')[1].Substring(1).Split(new char[] { '?' }, 2);
                            string request        = requestParts[0];
                            string[] parse        = request.Split('/');

                            string roomID = "";
                            Room r        = null;


                            string responseBuffer = "";
                            switch (parse[0])
                            {
                            case "uptime":
                                responseBuffer = ((int)((DateTime.Now - StartTime).TotalMilliseconds / 1000d)).ToString();
                                break;

                            case "l":
                                responseBuffer = "[";


                                //Lobby

                                responseBuffer += "[";
                                responseBuffer += "\"Lobby\",";
                                responseBuffer += "\"Lobby\",";
                                responseBuffer += "\"\",";
                                responseBuffer += "\"Admin\",";
                                responseBuffer += GetUsersInLobby().Count().ToString() + ",";
                                responseBuffer += "\"0\",";
                                responseBuffer += "\"N/A\",";
                                responseBuffer += "\"N/A\",";

                                userlist        = GetLobbyUsers();
                                responseBuffer += "\"" + userlist.TrimEnd(',') + "\"";
                                userlist        = "";
                                responseBuffer += "]";
                                responseBuffer += ",";


                                foreach (Room room in Rooms)
                                {
                                    if (!room.Secret && !room.Owner.ShadowBanned)
                                    {
                                        string playerlist;
                                        responseBuffer += "[";
                                        responseBuffer += "\"" + room.ID + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.Name) + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.Description) + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.Owner.User_Name) + "\",";
                                        responseBuffer += room.Users.Count + ",";
                                        responseBuffer += "\"" + room.Status.ToString() + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.CurrentSong.Name) + "\",";
                                        responseBuffer += "\"" + JsonSafe(room.CurrentSong.Artist) + "\",";

                                        userlist        = room.GetRoomUsers();
                                        responseBuffer += "\"" + userlist.TrimEnd(',') + "\"";
                                        userlist        = "";
                                        responseBuffer += "]";

                                        if (Rooms.Last() != room)
                                        {
                                            responseBuffer += ",";
                                        }
                                    }
                                }
                                responseBuffer += "]";
                                break;

//		case "a":
//			responseBuffer = "[";
//			User[] serverusers = User.GetUsersInServer();
//			{
//				foreach (User user in serverusers)
//				{
//					responseBuffer += "[";
//					responseBuffer += "\"" + user.User_Name + "\",";
//					responseBuffer += "],";
//				}
//			}
//			responseBuffer += "]";
//			break;


                            case "g":
                                roomID = parse[1];
                                r      = null;
                                foreach (Room room in Rooms)
                                {
                                    if (room.ID == roomID)
                                    {
                                        r = room;
                                        break;
                                    }
                                }

                                if (r == null || r.Secret)
                                {
                                    responseBuffer = "[]";
                                }
                                else
                                {
                                    User[] usersOrig = r.Users.ToArray();
                                    if (usersOrig.Length == 0)
                                    {
                                        responseBuffer = "[]";
                                    }
                                    else
                                    {
                                        User[] users    = (from user in usersOrig orderby user.SMOScore descending select user).ToArray();
                                        responseBuffer += "[[\"" + JsonSafe(r.Name) + "\",";
                                        responseBuffer += "\"" + JsonSafe(r.Description) + "\",";
                                        responseBuffer += "\"" + JsonSafe(r.CurrentSong.Artist + " - " + r.CurrentSong.Name) + "\",";
                                        if (r.CurrentSong.Time == 0)
                                        {
                                            responseBuffer += "false,";
                                        }
                                        else
                                        {
                                            responseBuffer += "\"" + (int)Math.Min(100, Math.Floor(100d / r.CurrentSong.Time * usersOrig[0].SongTime.ElapsedMilliseconds / 1000d)) + "%\",";
                                        }
                                        responseBuffer += "\"" + JsonSafe(r.ChatBuffer) + "\"";
                                        responseBuffer += "],";
                                        foreach (User user in users)
                                        {
                                            responseBuffer += "[";
                                            responseBuffer += user.User_ID + ",";
                                            responseBuffer += "\"" + JsonSafe(user.User_Name) + "\",";
                                            responseBuffer += "\"" + user.Combo + "\",";
                                            responseBuffer += user.SMOScore + ",";
                                            responseBuffer += "\"" + user.Grade + "\",";
                                            responseBuffer += "\"" + user.GameDifficulty + "\",";
                                            responseBuffer += "\"" + JsonSafe(user.GamePlayerSettings) + "\",";
                                            responseBuffer += "\"" + JsonSafe(user.GamePlayerSettings) + "\",";
                                            if (user.Notes == null)
                                            {
                                                for (int i = 0; i < 9; i++)
                                                {
                                                    responseBuffer += "\"0\",";
                                                }
                                            }
                                            else
                                            {
                                                responseBuffer += "\"" + JsonSafe(user.Notes[(int)NSNotes.Flawless].ToString()) + "\",";
                                                responseBuffer += "\"" + JsonSafe(user.Notes[(int)NSNotes.Perfect].ToString()) + "\",";
                                                responseBuffer += "\"" + JsonSafe(user.Notes[(int)NSNotes.Great].ToString()) + "\",";
                                                responseBuffer += "\"" + JsonSafe(user.Notes[(int)NSNotes.Good].ToString()) + "\",";
                                                responseBuffer += "\"" + JsonSafe(user.Notes[(int)NSNotes.Barely].ToString()) + "\",";
                                                responseBuffer += "\"" + JsonSafe(user.Notes[(int)NSNotes.Miss].ToString()) + "\",";
                                                responseBuffer += "\"" + JsonSafe(user.Notes[(int)NSNotes.Held].ToString()) + "\",";
                                                responseBuffer += "\"" + JsonSafe(user.Notes[(int)NSNotes.NG].ToString()) + "\",";
                                            }
                                            responseBuffer += "\"" + user.MaxCombo + "\",";
                                            responseBuffer += "\"" + user.percent + "\"";
                                            responseBuffer += "],";
                                        }
                                        responseBuffer += "]";
                                    }
                                }
                                break;

                            case "c":
                                if (IP != ServerConfig.Get("RTS_Trusted"))
                                {
                                    responseBuffer = "[]";
                                    break;
                                }

                                roomID           = parse[1];
                                string webuserid = parse[2];
                                string chatcolor = parse[3];
                                string data      = Uri.UnescapeDataString(parse[4]);
                                //string data = requestParts.Length == 3 ? Uri.UnescapeDataString(requestParts[3]);
                                Hashtable[] userRes = MySql.Query("select Username from users where id = " + webuserid + "");
                                if (userRes.Length != 1)
                                {
                                    break;
                                }

                                Hashtable u = userRes[0];

                                r = null;
                                lock (Rooms)
                                {
                                    foreach (Room room in Rooms)
                                    {
                                        if (room.ID == roomID)
                                        {
                                            r = room;
                                            break;
                                        }
                                    }


                                    AddLog("WebChat from " + u["Username"].ToString() + ": " + data);
                                    if (r != null && !r.Secret)
                                    {
                                        if (r.NoWebChat)
                                        {
                                            responseBuffer = "Web Chat Disabled on Room by Owner/OP";
                                            break;
                                        }
                                        string strName = u["Username"].ToString();

                                        SendChatAll(Func.ChatColor(chatcolor) + strName + Func.ChatColor("ffffff") + ": " + User.Utf8Encode(data), r);
                                    }
                                }

                                responseBuffer = "OK";
                                break;
                            }
                            writer.WriteLine("HTTP/1.1 200 OK");
                            writer.WriteLine("Content-Type: text/plain");
                            writer.WriteLine("access-control-allow-origin: *");
                            writer.WriteLine("access-control-allow-credentials: true");
                            //Breaks incorrectly calculated utf8
                            //writer.WriteLine("Content-Length: " + responseBuffer.Length);
                            writer.WriteLine("Connection: close");
                            writer.WriteLine();
                            writer.Write(responseBuffer);
                        }
                    }
                    catch (Exception ex)
                    {
                        AddLog("RTS request encountered '" + ex.GetType().Name + "' from " + IP, true);
                    }

                    stream.Close();
                    stream.Dispose();
                })).Start();
            }
        }
Ejemplo n.º 13
0
        public static void AddStats(User user)
        {
            if (user.CurrentRoom == null)
            {
                return;
            }

            if (user.CurrentRoom.CurrentSong == null)
            {
                return;
            }

            user.CurrentRoom.Status = RoomStatus.Ready;

            string Name     = MySql.AddSlashes(user.CurrentRoom.CurrentSong.Name);
            string Artist   = MySql.AddSlashes(user.CurrentRoom.CurrentSong.Artist);
            string SubTitle = MySql.AddSlashes(user.CurrentRoom.CurrentSong.SubTitle);

            int       songID = 0;
            Hashtable song   = Data.GetSong(Name, Artist, SubTitle);

            if (song != null)
            {
                songID = (int)song["ID"];

                if (!user.ShadowBanned)
                {
                    double songTime = user.SongTime.Elapsed.TotalSeconds;
                    if (songTime > (int)song["Time"])
                    {
                        MySql.Query("UPDATE songs SET Time=" + songTime.ToString().Replace(',', '.') + " WHERE ID=" + song["ID"]);
                    }
                }

                string playerSettings = MySql.AddSlashes(user.GamePlayerSettings);

                // Big-ass query right there...
                if (!user.ShadowBanned)
                {
                    MySql.Query("INSERT INTO stats (User,PlayerSettings,Song,Feet,Difficulty,Grade,Score,MaxCombo," +
                                "Note_0,Note_1,Note_Mine,Note_Miss,Note_Barely,Note_Good,Note_Great,Note_Perfect,Note_Flawless,Note_NG,Note_Held) VALUES(" +
                                user.User_Table["ID"].ToString() + ",'" + playerSettings + "'," + songID.ToString() + "," + user.GameFeet.ToString() + "," + ((int)user.GameDifficulty).ToString() + "," + ((int)user.Grade).ToString() + "," + user.Score.ToString() + "," + user.MaxCombo.ToString() + "," +
                                user.Notes[0].ToString() + "," + user.Notes[1].ToString() + "," + user.Notes[2].ToString() + "," + user.Notes[3].ToString() + "," + user.Notes[4].ToString() + "," + user.Notes[5].ToString() + "," + user.Notes[6].ToString() + "," + user.Notes[7].ToString() + "," + user.Notes[8].ToString() + "," + user.Notes[9].ToString() + "," + user.Notes[10].ToString() + ")");
                }
            }

            // Give player XP
            int XP = 0;

            for (int i = 3; i <= 8; i++)
            {
                XP += (i - 3) * user.Notes[i];
            }
            XP /= 6;

            user.SendChatMessage("You gained " + Func.ChatColor("aaaa00") + XP.ToString() + Func.ChatColor("ffffff") + " XP!");

            if (!user.ShadowBanned)
            {
                MySql.Query("UPDATE users SET XP=XP+" + XP.ToString() + " WHERE ID=" + user.User_ID.ToString());
            }
        }