Exemplo n.º 1
0
        public async Task <PaginatedList <Song> > GetSongsBySearchAsync(SongParameters songParameters)
        {
            var search_url =
                $@"https://c.y.qq.com/soso/fcgi-bin/client_search_cp?aggr=1&cr=1&flag_qc=0&format=json&p={songParameters.PageIndex + 1}&w={songParameters.Keywords}";
            var json = await HttpHelper.HttpGetAsync(search_url, contentType : "application/json");

            var jObject     = (JObject)JsonConvert.DeserializeObject(json);
            var jsonData    = (JObject)jObject["data"];
            var jsonSong    = (JObject)jsonData["song"];
            var currentPage = int.Parse(jsonSong["curpage"].ToString());
            var pageSize    = int.Parse(jsonSong["curnum"].ToString());
            var totalCounts = int.Parse(jsonSong["totalnum"].ToString());

            var jsonArray = (JArray)jsonSong["list"];

            var songList = new Collection <Song>();

            for (var i = 0; i < jsonArray.Count; i++)
            {
                var song = await GetSongAsync((JObject)jsonArray[i]);

                songList.Add(song);
            }

            return(new PaginatedList <Song>(currentPage, pageSize, totalCounts, songList));
        }
Exemplo n.º 2
0
        public async Task <PaginatedList <Song> > GetAllAsync(SongParameters parameters)
        {
            var json = await HttpHelper.HttpGetAsync(TopUrl, contentType : "application/json");

            var jObject   = (JObject)JsonConvert.DeserializeObject(json);
            var jsonArray = (JArray)jObject["songlist"];

            var songList = new Collection <Song>();

            var countList = new List <int>();

            for (var i = 0; i < jsonArray.Count; i++)
            {
                countList.Add(i);
            }
            var takeList = countList.Skip(parameters.PageIndex * parameters.PageSize).Take(parameters.PageSize);

            foreach (var i in takeList)
            {
                var data = (JObject)jsonArray[i]["data"];
                var song = await GetSongAsync(data);

                song.Rank = int.Parse(jsonArray[i]["cur_count"].ToString());

                songList.Add(song);
            }

            return(new PaginatedList <Song>(parameters.PageIndex, parameters.PageSize, countList.Count, songList));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Checks to see if a song is in the database already.  If it isn't, the song is
        /// added to the database with a single vote.  If it is, add the vote to that song.
        /// </summary>
        /// <param name="song">The song object to vote on</param>
        /// <param name="vote">The vote. True if upvote, false if downvote.</param>
        /// <param name="userID">The ID of the user who voted</param>
        internal SongParameters VoteOnSong(SongParameters song, bool vote, int userID)
        {
            if (song.ID == -1)
            {
                song.ID = GetID(song);                                  // Song has no ID.  Search the server
            }
            if (song.ID == -1)
            {
                // Song is not in the database.  Insert it into the database.
                song.ID     = GetNextAvailableID("uploadedsongs");
                song.score  = (vote) ? 1 : -1;
                song.userID = userID;
                insertData(song);
                addVoteToUserTable(userID, song.ID, vote);
            }
            else
            {
                int voteAmount = checkAndChangeVote(userID, song.ID, vote);
                updateScore(song.ID, voteAmount);

                object score = returnItem(song.ID, "voteScore", "uploadedsongs");
                if (score != null && score is int)
                {
                    song.score = (int)score;
                }
                else
                {
                    throw new DatabaseException("DATABASE ERROR: Invalid data type returned");
                }
            }

            return(song);
        }
Exemplo n.º 4
0
        private void loadSong(bool nextSong)
        {
            stopSong();
            if (songPos >= 0)
            {
                int            tempScore = score;
                SongParameters tempSong  = backlog[songPos];
                UserToken      tempUser  = currentUser;
                int            tempGenre = curGenre;
                new Thread(() => sendScore(tempScore, tempSong, tempUser, tempGenre)).Start();
            }
            resetPlayBar();

            if (nextSong)
            {
                songPos++;
            }
            else if (songPos > 0)
            {
                songPos--;
            }

            if (songPos < 0 || songPos > backlog.Count)
            {
                return;
            }

            foreach (Setting setting in settings)
            {
                if (setting.isChecked())
                {
                    setting.randomize();
                }
            }

            if (songPos >= backlog.Count)
            {
                backlog.Add(new SongParameters(seed.getIntValue(), tempo.getIntValue(), genre.getStringValue()));
                if (backlog.Count > Properties.Settings.Default.maxSongs)
                {
                    backlog.RemoveAt(0);
                    songPos--;
                }
            }
            else
            {
                genre.setValue(backlog[songPos].genre);
                tempo.setValue(backlog[songPos].tempo + "");
                seed.setValue(backlog[songPos].seed + "");
            }

            player.Open("");
            songLen = generator.generate(backlog[songPos]);
            player.Open("temp.mid");
            playSong();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Gets a list of songs that match the given SongParameters object
        /// </summary>
        /// <param name="numSongs">The number of songs</param>
        /// <param name="seed">(optional) the seed to filter by</param>
        /// <param name="tempo">(optional) the tempo to filter by</param>
        /// <param name="genre">(optional) the genre to filter by</param>
        /// <param name="userID">(optional) the user ID to filter by</param>
        /// <returns></returns>
        internal List <SongParameters> GetSongList(int numSongs, string genre, string username)
        {
            MySqlConnection conn    = new MySqlConnection(connString);
            MySqlCommand    command = conn.CreateCommand();

            if (genre != null)
            {
                command.CommandText = "Select iduploadedsongs from uploadedsongs where genre like '%" + genre + "%' order by voteScore desc limit " + numSongs;
            }
            else if (username != null)
            {
                command.CommandText = "Select iduploadedsongs from uploadedsongs where idusers like '%" + GetID(username) + "%' order by voteScore desc limit " + numSongs;
            }
            else
            {
                command.CommandText = "Select iduploadedsongs from uploadedsongs order by voteScore desc limit " + numSongs;
            }

            int score = 0;

            int[] idArray = new int[numSongs];
            int   i       = -1;

            try {
                conn.Open();
                MySqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    i++;
                    score      = (int)reader["iduploadedsongs"];
                    idArray[i] = score;
                }
            } catch (MySqlException ex) {
                throw new DatabaseException("SQL Exception: " + ex.Message, ex);                        // Propagate the exception upwards after handling the finally block
            } finally {
                conn.Close();
            }

            List <SongParameters> list = new List <SongParameters>();

            for (int j = 0; j < numSongs; j++)
            {
                int tempId = idArray[j];
                if (tempId == 0)
                {
                    break;
                }

                SongParameters song = GetSong(tempId);

                list.Add(song);
            }

            return(list);
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Search(SongParameters songParameters)
        {
            ValidateMapping <SongResource, Song>(songParameters.OrderBy);
            ValidateFields <SongResource>(songParameters.Fields);
            if (Results.Count != 0)
            {
                return(Results.First());
            }

            var list = await _repository.GetSongsBySearchAsync(songParameters);

            var resources = _mapper.Map <IEnumerable <Song>, IEnumerable <SongResource> >(list);

            var shapedResources = resources.ToDynamicIEnumerable(songParameters.Fields);

            CreateHeader(songParameters, list, "GetSongsBySearch", false);

            return(Ok(new OkMessage(shapedResources)));
        }
Exemplo n.º 7
0
        private void sendScore(int tempScore, SongParameters tempSong, UserToken tempUser, int tempGenre)
        {
            if (server.Test())
            {
                if (tempScore > 0)
                {
                    server.SendRequest(new BBRequest(tempSong, true, tempUser));
                }
                else if (tempScore < 0)
                {
                    server.SendRequest(new BBRequest(tempSong, false, tempUser));
                }

                createRedditThreads();

                if (!this.IsDisposed)
                {
                    this.Invoke((MethodInvoker) delegate { this.Invalidate(); });
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Searches the database for a song that matches the given song.
        /// If there is a match, returns the ID.  If not, returns -1
        /// </summary>
        /// <param name="song">Song to search the database for</param>
        /// <returns>ID of the song on the server</returns>
        internal int GetID(SongParameters song)
        {
            MySqlConnection conn    = new MySqlConnection(connString);
            MySqlCommand    command = conn.CreateCommand();

            command.CommandText = "Select iduploadedsongs from uploadedsongs where genre like '%" + song.genre + "%' and songseed like '%" + song.seed + "%' and tempo like '%" + song.tempo + "%'";
            int returnId = -1;

            try {
                conn.Open();
                MySqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    returnId = (int)reader["iduploadedsongs"];
                }
            } catch (MySqlException ex) {
                throw new DatabaseException("SQL Exception: " + ex.Message, ex);                        // Propagate the exception upwards after handling the finally block
            } finally {
                conn.Close();
            }

            return(returnId);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Returns the given song with updated ID, score and user data.
        ///  Does not add the song to the database if it isn't already there.
        /// </summary>
        /// <param name="song">Song to refresh</param>
        /// <returns>A SongParameters object that represents the song</returns>
        internal SongParameters RefreshSong(SongParameters song)
        {
            if (song.ID == -1)
            {
                song.ID = GetID(song);                                  // Song has no ID.  Search the server
            }
            if (song.ID == -1)
            {
                // Song is not in the database. Return score of 0 and userID of -1.
                song.score  = 0;
                song.userID = -1;
            }
            else
            {
                object score = returnItem(song.ID, "voteScore", "uploadedsongs");
                if (score != null && score is int)
                {
                    song.score = (int)score;
                }
                else
                {
                    throw new DatabaseException("DATABASE ERROR: Invalid data type returned");
                }

                object userID = returnItem(song.ID, "idusers", "uploadedsongs");
                if (userID != null && userID is int)
                {
                    song.userID = (int)userID;
                }
                else
                {
                    throw new DatabaseException("DATABASE ERROR: Invalid data type returned");
                }
            }

            return(song);
        }
Exemplo n.º 10
0
 public SingleSong(SongParameters song)
 {
     this.song = song;
 }
Exemplo n.º 11
0
 public BBResponse(SongParameters song)
 {
     responseType = new SingleSong(song);
 }
Exemplo n.º 12
0
 public RequestScore(SongParameters song, UserToken userInfo) : base(userInfo)
 {
     this.song = song;
 }
Exemplo n.º 13
0
 public UpDownVote(SongParameters song, bool vote, UserToken userInfo) : base(userInfo)
 {
     this.song = song;
     this.vote = vote;
 }
Exemplo n.º 14
0
 /// <summary>
 /// Sends a request for the score of a single song.
 ///
 /// The response will contain a single SongParameters item with the song and it's score
 /// </summary>
 /// <param name="song">Song to check the score of</param>
 /// <param name="userInfo">The user authentication token</param>
 public BBRequest(SongParameters song, UserToken userInfo)
 {
     requestType = new RequestScore(song, userInfo);
 }
Exemplo n.º 15
0
        /// <summary>
        /// Child thread function.
        /// Handles a connection with a single client.
        /// </summary>
        /// <param name="client">The TcpClient object</param>
        private void HandleConnectionWithClient(object client)
        {
            TcpClient     tcpClient     = (TcpClient)client;
            NetworkStream networkStream = tcpClient.GetStream();
            IPAddress     address       = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address;

            Log("Remote client connected", address, 0);

            object message = Message.Recieve(networkStream);

            while (tcpClient.Connected && message != null)
            {
                if (message is string && message as string == "Test")
                {
                    // A test message was recieved.  Send a response back.
                    Log("Recieved a connection test request", address, 1);
                    Message.TestMsg(networkStream);
                }
                else if (message is AuthRequest)
                {
                    // An AuthRequest was receieved.  Authenticate the user and reply with a UserToken.
                    AuthRequest req = message as AuthRequest;
                    Log("Recieved an authentication request", address, 1);

                    UserToken token = null;
                    if (req.register)
                    {
                        Log("    Registering New User: "******"    Registration Successful", address, 2);
                            }
                            else
                            {
                                Log("    Registration Failed", address, 2);
                            }
                        } catch (DatabaseException ex) {
                            Log("DATABASE ERROR: Registration could not proceed", address, 0);
                            Log(ex.Message, 0);
                        }
                    }
                    else
                    {
                        Log("    Authenticating User: "******"    Authentication Successful", address, 2);
                            }
                            else
                            {
                                Log("    Authentication Failed", address, 2);
                            }
                        } catch (DatabaseException ex) {
                            Log("DATABASE ERROR: Authentication could not proceed", address, 0);
                            Log(ex.Message, 0);
                        }
                    }

                    Message.Send(networkStream, new AuthResponse(token));
                }
                else if (message is TokenVerifyRequest)
                {
                    // A TokenVerifyRequest was recieved.  Test the token for validity.
                    Log("Recieved a token verification request", address, 1);
                    TokenVerifyRequest req = message as TokenVerifyRequest;

                    Log("    User: "******"    Expires: " + req.token.expires, address, 2);
                    Log("    Token: " + req.token.token, address, 2);

                    try {
                        bool valid;

                        if (database.VerifyToken(req.token) != 0)
                        {
                            Log("    Verification Successful", address, 2);
                            valid = true;
                        }
                        else
                        {
                            Log("    Verification Failed", address, 2);
                            valid = false;
                        }

                        Message.Send(networkStream, new TokenVerifyResponse(valid));
                    } catch (DatabaseException ex) {
                        Log("DATABASE ERROR: Could not process request", address, 0);
                        Log(ex.Message, 0);
                        Message.Send(networkStream, new BBResponse("Database", "An unknown database error occured.  Could not process request."));
                    }
                }
                else if (message is BBRequest)
                {
                    try {
                        // A BBRequest was recieved.  Process the request
                        BBRequest bbmessage = message as BBRequest;
                        Log("Received a " + bbmessage.requestType + " request", address, 1);

                        // Authenticate the user
                        int userID;
                        if (bbmessage.requestType.userToken == null)
                        {
                            Log("    No user supplied.  Processing as anonymous.", address, 2);
                            userID = -1;
                        }
                        else
                        {
                            Log("    Username: "******"    Expires: " + bbmessage.requestType.userToken.expires, address, 2);
                            Log("    Token: " + bbmessage.requestType.userToken.token, address, 2);
                            userID = database.VerifyToken(bbmessage.requestType.userToken);
                        }

                        if (userID == 0)
                        {
                            Log("    User Authentication failed", address, 1);
                            Message.Send(networkStream, new BBResponse());
                        }
                        else
                        {
                            if (bbmessage.requestType is BBRequest.UpDownVote)
                            {
                                // Upload and vote on a song
                                BBRequest.UpDownVote req = bbmessage.requestType as BBRequest.UpDownVote;

                                Log("    " + (req.vote ? "Upvote" : "Downvote") + " Request", address, 2);
                                Log("        ID: " + req.song.ID, address, 3);
                                Log("     Genre: " + req.song.genre, address, 3);
                                Log("     Tempo: " + req.song.tempo, address, 3);
                                Log("      Seed: " + req.song.seed, address, 3);

                                SongParameters song = database.VoteOnSong(req.song, req.vote, userID);
                                Message.Send(networkStream, new BBResponse(song));

                                Log("    Response has ID of " + song.ID + " and score of " + song.score, address, 2);
                            }
                            else if (bbmessage.requestType is BBRequest.RequestScore)
                            {
                                // Request the score of a song
                                BBRequest.RequestScore req = bbmessage.requestType as BBRequest.RequestScore;

                                Log("        ID: " + req.song.ID, address, 3);
                                Log("     Genre: " + req.song.genre, address, 3);
                                Log("     Tempo: " + req.song.tempo, address, 3);
                                Log("      Seed: " + req.song.seed, address, 3);

                                SongParameters song = database.RefreshSong(req.song);
                                Message.Send(networkStream, new BBResponse(song));

                                Log("    Response has ID of " + song.ID + " and score of " + song.score, address, 2);
                            }
                            else if (bbmessage.requestType is BBRequest.RequestSongs)
                            {
                                // Request a list of songs
                                BBRequest.RequestSongs req = bbmessage.requestType as BBRequest.RequestSongs;

                                List <SongParameters> songList = database.GetSongList(req.num, req.genre, req.username);
                                Message.Send(networkStream, new BBResponse(songList));

                                Log("    Returned " + songList.Count + " songs", address, 2);
                            }
                            else
                            {
                                Log("BBREQUEST ERROR: Unknown BBRequest type '" + bbmessage.GetType() + "'", address, 0);
                                Message.Send(networkStream, new BBResponse("BBRequest", "Unknown BBRequest type '" + bbmessage.GetType() + "'"));
                            }
                        }
                    } catch (DatabaseException ex) {
                        Log("DATABASE ERROR: Could not process request", address, 0);
                        Log(ex.Message, 0);
                        Message.Send(networkStream, new BBResponse("Database", "An unknown database error occured.  Could not process request."));
                    } catch (System.IO.IOException ex) {
                        Log("IO ERROR: Could not send response", address, 0);
                        Log(ex.Message, 0);
                    }
                }
                else
                {
                    Log("Unknown request type '" + message.GetType() + "'", address, 0);
                }

                message = Message.Recieve(networkStream);
            }

            Log("Remote client disconnected", address, 0);

            tcpClient.Close();
        }
Exemplo n.º 16
0
        private void insertData(SongParameters song)
        {
            MySqlConnection conn = new MySqlConnection(connString);

            SQLNonQuery(conn, "Insert into uploadedsongs (iduploadedsongs,genre,songseed,tempo,voteScore, idusers) values('" + song.ID + "','" + song.genre + "','" + song.seed + "','" + song.tempo + "','" + song.score + "','" + song.userID + "')");
        }
Exemplo n.º 17
0
 /// <summary>
 /// Sends an upload request with a single song and either an upvote or a downvote.
 /// The server will check the database for that song.  If the song exists, it will
 /// add the vote to it, otherwise it will add the song to the server and save it
 /// with the vote.
 ///
 /// The response will contain a single SongParameters item with the song and it's score
 /// </summary>
 /// <param name="song">Song to upload</param>
 /// <param name="upOrDownvote">Vote. True if an upvote, false otherwise.</param>
 /// <param name="userInfo">The user authentication token</param>
 public BBRequest(SongParameters song, bool upOrDownvote, UserToken userInfo)
 {
     requestType = new UpDownVote(song, upOrDownvote, userInfo);
 }
Exemplo n.º 18
0
        private int logLevel;           // How verbose the logs should be.  Higher is more verbose.

        /// <summary>
        /// Starts up the server
        /// </summary>
        public static void Main()
        {
            // Create a new server that listens on port 3000;
            //Database database = new Database("Server=localhost;Port=3306;Database=songdatabase;Uid=root;password=joeswanson;");
            //Database database = new Database("Server=68.234.183.70;Port=3001;Database=songdatabase;Uid=BlottoServer;password=JJLrDtcrfvjym8gh1zUVklF19KDf1CTM;");
            //Database database = new Database("Server=BlottoBeats.db.11772669.hostedresource.com;Port=3306;Database=BlottoBeats;Uid=BlottoBeats;password=JoeSwanson307!;");
            //Server server = new Server(3000, database, "server.log", 3);
            Database database = null;
            Server   server   = null;

            // Server startup screen
            CommandLine.WriteLine("---------------------------------------------");
            CommandLine.WriteLine("      BlottoBeats Server v1.0 (Stopped)");
            CommandLine.WriteLine("---------------------------------------------");
            CommandLine.WriteLine("Host ID: " + Properties.Settings.Default.hostID);
            CommandLine.WriteLine("Port:    " + Properties.Settings.Default.port);
            CommandLine.WriteLine();
            CommandLine.WriteLine("Database Name: " + Properties.Settings.Default.databaseName);
            CommandLine.WriteLine();
            CommandLine.WriteLine("Username: "******"---------------------------------------------");
            CommandLine.WriteLine("Type upstart <password> to log into the database and start the server.");
            CommandLine.WriteLine("Type help or ? for more commands.");

            while (true)
            {
                CommandLine line = CommandLine.Prompt();

                switch (line.command.ToLower())
                {
                // SERVER COMMANDS
                case "start":
                    if (server != null && server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: Can't start the server, the server is already started");
                    }
                    else if (database == null || server == null)
                    {
                        CommandLine.WriteLine("ERROR: The update command needs to be run first");
                    }
                    else
                    {
                        server.Start();
                    }
                    break;

                case "stop":
                    if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: Can't stop the server, the server is already stopped");
                    }
                    else
                    {
                        server.Stop();
                    }
                    break;

                case "restart":
                    if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: Can't restart the server, the server is stopped");
                    }
                    else
                    {
                        server.Restart();
                    }
                    break;

                case "update":
                case "updatedb":
                case "updatedatabase":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else if (server != null && server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: Can't update the database if the server is running.  Stop the server first.");
                    }
                    else
                    {
                        database = new Database(Properties.Settings.Default.hostID,
                                                Properties.Settings.Default.port,
                                                Properties.Settings.Default.databaseName,
                                                Properties.Settings.Default.userID,
                                                line.args[0]);
                        server = new Server(3000, database, "server.log", 3);
                        CommandLine.WriteLine("Database updated successfully.");
                    }
                    break;

                case "upstart":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else if (server != null && server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: Can't update the database if the server is running.  Stop the server first.");
                    }
                    else
                    {
                        database = new Database(Properties.Settings.Default.hostID,
                                                Properties.Settings.Default.port,
                                                Properties.Settings.Default.databaseName,
                                                Properties.Settings.Default.userID,
                                                line.args[0]);
                        server = new Server(3000, database, "server.log", 3);
                        CommandLine.WriteLine("Database updated successfully.");

                        server.Start();
                    }
                    break;

                // DATABASE COMMANDS
                case "dbhost":
                case "dbhostid":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else
                    {
                        Properties.Settings.Default.hostID = line.args[0];
                        Properties.Settings.Default.Save();
                        CommandLine.WriteLine("Setting is updated.  You need to run the update command in order for the changes to be applied to the server.");
                    }
                    break;

                case "dbport":
                    int port;
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else if (int.TryParse(line.args[0], out port) && port > 1024 && port <= 65535)
                    {
                        Properties.Settings.Default.port = port;
                        Properties.Settings.Default.Save();
                        CommandLine.WriteLine("Setting is updated.  You need to run the update command in order for the changes to be applied to the server.");
                    }
                    else
                    {
                        CommandLine.WriteLine("ERROR: The argument must be an integer between 1024 and 65535");
                    }
                    break;

                case "database":
                case "databasename":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else
                    {
                        Properties.Settings.Default.databaseName = line.args[0];
                        Properties.Settings.Default.Save();
                        CommandLine.WriteLine("Setting is updated.  You need to run the update command in order for the changes to be applied to the server.");
                    }
                    break;

                case "dbuser":
                case "dbuserid":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else
                    {
                        Properties.Settings.Default.userID = line.args[0];
                        Properties.Settings.Default.Save();
                        CommandLine.WriteLine("Setting is updated.  You need to run the update command in order for the changes to be applied to the server.");
                    }
                    break;

                case "info":
                case "dbinfo":
                    string health = "Stopped";
                    if (server != null && server.IsAlive())
                    {
                        health = "Running";
                    }

                    CommandLine.WriteLine("---------------------------------------------");
                    CommandLine.WriteLine("      BlottoBeats Server v1.0 (" + health + ")");
                    CommandLine.WriteLine("---------------------------------------------");
                    CommandLine.WriteLine("Host ID: " + Properties.Settings.Default.hostID);
                    CommandLine.WriteLine("Port:    " + Properties.Settings.Default.port);
                    CommandLine.WriteLine();
                    CommandLine.WriteLine("Database Name: " + Properties.Settings.Default.databaseName);
                    CommandLine.WriteLine();
                    CommandLine.WriteLine("Username: "******"---------------------------------------------");
                    break;

                // USER ACCOUNT COMMANDS
                case "newaccount":
                    if (line.numArgs < 2)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires two arguments");
                    }
                    else if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: The server is offline");
                    }
                    else
                    {
                        try {
                            UserToken token = database.Authenticate(new Credentials(line.args[0], line.args[1]), true);
                            if (token != null)
                            {
                                CommandLine.WriteLine("Registration Successful");
                            }
                            else
                            {
                                CommandLine.WriteLine("Registration Failed");
                            }
                        } catch (DatabaseException ex) {
                            CommandLine.WriteLine("DATABASE ERROR: Registration could not proceed");
                            CommandLine.WriteLine(ex.Message);
                        }
                    }
                    break;

                case "deleteaccount":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: The server is offline");
                    }
                    else
                    {
                        try {
                            int id = database.GetID(line.args[0]);
                            if (id != 0)
                            {
                                database.deleteUser(id);
                                CommandLine.WriteLine("User '" + line.args[0] + "' deleted.");
                            }
                            else
                            {
                                CommandLine.WriteLine("ERROR:User '" + line.args[0] + "' does not exist");
                            }
                        } catch (DatabaseException ex) {
                            CommandLine.WriteLine("DATABASE ERROR: User could not be deleted");
                            CommandLine.WriteLine(ex.Message);
                        }
                    }
                    break;

                case "resetpassword":
                    if (line.numArgs < 2)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires two arguments");
                    }
                    else if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: The server is offline");
                    }
                    else
                    {
                        try {
                            Credentials credentials = new Credentials(line.args[0], line.args[1]);
                            int         id          = database.GetID(credentials.username);
                            if (id != 0)
                            {
                                database.changePassword(id, credentials.GenerateHash());
                                CommandLine.WriteLine("Password Change Successful");
                            }
                            else
                            {
                                CommandLine.WriteLine("ERROR:User '" + credentials.username + "' does not exist");
                            }
                        } catch (DatabaseException ex) {
                            CommandLine.WriteLine("DATABASE ERROR: Password could not be changed");
                            CommandLine.WriteLine(ex.Message);
                        }
                    }
                    break;

                case "refreshtoken":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: The server is offline");
                    }
                    else
                    {
                        try {
                            if (database.RefreshToken(line.args[0]))
                            {
                                CommandLine.WriteLine("Refreshed token");
                            }
                            else
                            {
                                CommandLine.WriteLine("User '" + line.args[0] + "' does not exist");
                            }
                        } catch (DatabaseException ex) {
                            CommandLine.WriteLine("DATABASE ERROR: Refresh could not proceed");
                            CommandLine.WriteLine(ex.Message);
                        }
                    }
                    break;

                case "whois":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: The server is offline");
                    }
                    else
                    {
                        try {
                            int id;
                            if (int.TryParse(line.args[0], out id))
                            {
                                string name = database.GetUsername(id);
                                if (name != null)
                                {
                                    CommandLine.WriteLine("Username of user " + id + " is '" + name + "'");
                                }
                                else
                                {
                                    CommandLine.WriteLine("User " + id + " does not exist");
                                }
                            }
                            else
                            {
                                CommandLine.WriteLine("ERROR: Argument 1 must be an integer");
                            }
                        } catch (DatabaseException ex) {
                            CommandLine.WriteLine("DATABASE ERROR: Refresh could not proceed");
                            CommandLine.WriteLine(ex.Message);
                        }
                    }
                    break;

                // SONG COMMANDS
                case "newsong":
                    if (line.numArgs < 3)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires three arguments");
                    }
                    else if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: The server is offline");
                    }
                    else
                    {
                        try {
                            int seed, tempo;
                            if (line.numArgs < 4)
                            {
                                if (int.TryParse(line.args[0], out seed) && int.TryParse(line.args[1], out tempo))
                                {
                                    SongParameters song = new SongParameters(seed, tempo, line.args[2]);
                                    song = database.VoteOnSong(song, true, -1);

                                    CommandLine.WriteLine("Created new song with ID '" + song.ID + "' as anonymous");
                                }
                                else
                                {
                                    CommandLine.WriteLine("Arguments 1 and 2 must be integers");
                                }
                            }
                            else
                            {
                                int userID;
                                if (int.TryParse(line.args[0], out seed) && int.TryParse(line.args[1], out tempo) && int.TryParse(line.args[3], out userID))
                                {
                                    SongParameters song = new SongParameters(seed, tempo, line.args[2], userID);
                                    song = database.VoteOnSong(song, true, -1);

                                    CommandLine.WriteLine("Created new song with ID '" + song.ID + "' belonging to user " + userID);
                                }
                                else
                                {
                                    CommandLine.WriteLine("Arguments 1, 2, and 4 must be integers");
                                }
                            }
                        } catch (DatabaseException ex) {
                            CommandLine.WriteLine("DATABASE ERROR: Could not create song");
                            CommandLine.WriteLine(ex.Message);
                        }
                    }
                    break;

                case "deletesong":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: The server is offline");
                    }
                    else
                    {
                        try {
                            int id;
                            if (int.TryParse(line.args[0], out id) && database.SongExists(id))
                            {
                                database.deleteSong(id);
                                CommandLine.WriteLine("Song '" + id + "' deleted.");
                            }
                            else
                            {
                                CommandLine.WriteLine("ERROR:Song '" + id + "' does not exist");
                            }
                        } catch (DatabaseException ex) {
                            CommandLine.WriteLine("DATABASE ERROR: Song could not be deleted");
                            CommandLine.WriteLine(ex.Message);
                        }
                    }
                    break;

                case "setscore":
                    if (line.numArgs < 2)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires two arguments");
                    }
                    else if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: The server is offline");
                    }
                    else
                    {
                        try {
                            int id, score;
                            if (int.TryParse(line.args[0], out id) && int.TryParse(line.args[1], out score) && database.SongExists(id))
                            {
                                database.changeVoteScore(id, score);
                                CommandLine.WriteLine("Song " + id + " score set to " + score);
                            }
                            else
                            {
                                CommandLine.WriteLine("ERROR:Song " + id + " does not exist");
                            }
                        } catch (DatabaseException ex) {
                            CommandLine.WriteLine("DATABASE ERROR: Score could not be changed");
                            CommandLine.WriteLine(ex.Message);
                        }
                    }
                    break;

                case "songinfo":
                    if (line.numArgs < 1)
                    {
                        CommandLine.WriteLine("ERROR: The command '" + line.command + "' requires an argument");
                    }
                    else if (server == null || !server.IsAlive())
                    {
                        CommandLine.WriteLine("ERROR: The server is offline");
                    }
                    else
                    {
                        try {
                            int id;
                            if (int.TryParse(line.args[0], out id))
                            {
                                if (database.SongExists(id))
                                {
                                    SongParameters song = database.GetSong(id);
                                    CommandLine.WriteLine("Song " + song.ID);
                                    CommandLine.WriteLine();
                                    CommandLine.WriteLine("Seed:  " + song.seed);
                                    CommandLine.WriteLine("Tempo: " + song.tempo);
                                    CommandLine.WriteLine("Genre: " + song.genre);
                                    CommandLine.WriteLine();
                                    CommandLine.WriteLine("Score: " + song.score);
                                    CommandLine.WriteLine("User:  "******"Song " + id + " does not exist");
                                }
                            }
                            else
                            {
                                CommandLine.WriteLine("ERROR: Argument 1 must be an integer");
                            }
                        } catch (DatabaseException ex) {
                            CommandLine.WriteLine("DATABASE ERROR: Could not get song info");
                            CommandLine.WriteLine(ex.Message);
                        }
                    }
                    break;

                // Shell commands
                case "quit":
                case "exit":
                    if (server != null && server.IsAlive())
                    {
                        server.Stop();
                    }
                    return;

                case "help":
                case "?":
                    CommandLine.WriteLine("-------------------------");
                    CommandLine.WriteLine("      COMMAND LIST");
                    CommandLine.WriteLine("-------------------------");
                    CommandLine.WriteLine("SERVER COMMANDS");
                    CommandLine.WriteLine("Start");
                    CommandLine.WriteLine("    Starts the server");
                    CommandLine.WriteLine("Stop");
                    CommandLine.WriteLine("    Stops the server");
                    CommandLine.WriteLine("Restart");
                    CommandLine.WriteLine("    Restarts the server");
                    CommandLine.WriteLine("Update <password>");
                    CommandLine.WriteLine("    Modifies the database according to the changes.  The server must be stopped.");
                    CommandLine.WriteLine("Upstart <password>");
                    CommandLine.WriteLine("    Modifies the database according to the changes and starts the server.  The server must be stopped.");
                    CommandLine.WriteLine();
                    CommandLine.WriteLine("DATABASE COMMANDS");
                    CommandLine.WriteLine("DBHost/DBHostID <new ID>");
                    CommandLine.WriteLine("    Changes the hostID of the database.  Requires an update to take effect.");
                    CommandLine.WriteLine("DBPort <new Port>");
                    CommandLine.WriteLine("    Changes the port of the database.  Requires an update to take effect.");
                    CommandLine.WriteLine("Database/DatabaseName <new name>");
                    CommandLine.WriteLine("    Changes the name of the database.  Requires an update to take effect.");
                    CommandLine.WriteLine("DBUser/DBUserID <new id>");
                    CommandLine.WriteLine("    Changes the userID to use with the database.  Requires an update to take effect.");
                    CommandLine.WriteLine("DBInfo");
                    CommandLine.WriteLine("    Displays information about the server.");
                    CommandLine.WriteLine();
                    CommandLine.WriteLine("USER ACCOUNT COMMANDS");
                    CommandLine.WriteLine("Newaccount <username> <password>");
                    CommandLine.WriteLine("    Creates a new user account with the given username and password.");
                    CommandLine.WriteLine("Deleteaccount <username>");
                    CommandLine.WriteLine("    Deletes a user account with the given username.");
                    CommandLine.WriteLine("Resetpassword <username> <password>");
                    CommandLine.WriteLine("    Resets the password of the given username to the given password.");
                    CommandLine.WriteLine("Refreshtoken <username>");
                    CommandLine.WriteLine("    Refreshes the token associated with the given user account.");
                    CommandLine.WriteLine("Whois <id>");
                    CommandLine.WriteLine("    Returns the username of the user with the given ID.");
                    CommandLine.WriteLine();
                    CommandLine.WriteLine("SONG COMMANDS");
                    CommandLine.WriteLine("Newsong <seed> <tempo> <genre> [<userID>]");
                    CommandLine.WriteLine("    Adds a new song to the database with the given seed, tempo, and genre, and optionally, userID.  Displays the ID of the newly-added song.");
                    CommandLine.WriteLine("Deletesong <id>");
                    CommandLine.WriteLine("    Removes the given song from the database.");
                    CommandLine.WriteLine("Setscore <id> <score>");
                    CommandLine.WriteLine("    Sets the score of a given song to the given score.");
                    CommandLine.WriteLine("Songinfo <id>");
                    CommandLine.WriteLine("    Gets all the info about the given song.");

                    break;

                default:
                    CommandLine.WriteLine("'" + line.command + "' is not a valid command.  Type help or ? for a list of commands.");
                    break;
                }
            }
        }