public HTTPResponse PostProcessing(HTTPResponse response) { throw new NotImplementedException(); }
public override HTTPResponse GetResponse(HTTPRequest request) //OVERRIDE GetResponse function { HTTPResponse response = new HTTPResponse(200); //get request and store value string username = request.getRequestByKey("user"); string password = request.getRequestByKey("password"); string following = request.getRequestByKey("follow"); string message = request.getRequestByKey("message"); string[] Choose = request.Filename.Split("?"); //Determine between users and following if (Choose[0] == "users") { //cases for each method if (request.Method == "GET") { string json = JsonConvert.SerializeObject(Get_All_User()); response.body = Encoding.UTF8.GetBytes(json); } if (request.Method == "POST") { try { Twitter.AddUser(username, password); response.body = Encoding.UTF8.GetBytes("200 OK"); } catch (Exception) { response.status = 403; response.body = Encoding.UTF8.GetBytes("403 User already exists"); } } if (request.Method == "DELETE") { Twitter twitter = new Twitter(username); try { twitter.Del_User(username); //use Del_User to delete user response.body = Encoding.UTF8.GetBytes("200 OK"); } catch (Exception) { response.status = 404; response.body = Encoding.UTF8.GetBytes("404 User not exists"); } } } //Determine between users and following if (Choose[0] == "following") { Twitter twitter = new Twitter(username); //cases for each method if (request.Method == "GET") { string json = JsonConvert.SerializeObject(GetFollowing(username)); response.body = Encoding.UTF8.GetBytes(json); } if (request.Method == "POST") { if (Twitter.Check_Username(following)) { twitter.AddFollowing(following); response.body = Encoding.UTF8.GetBytes("200 OK"); } else { response.status = 404; response.body = Encoding.UTF8.GetBytes("404 User not exists"); } } if (request.Method == "DELETE") { try { twitter.RemoveFollowing(following); response.body = Encoding.UTF8.GetBytes("200 OK"); } catch (Exception) { response.status = 404; response.body = Encoding.UTF8.GetBytes("404 User not exists"); } } } if (Choose[0] == "tweets") { Twitter twitter = new Twitter(username); if (request.Method == "GET") { try { string timeline = request.getRequestByKey("timeline"); if (timeline == "following") { string json = JsonConvert.SerializeObject(twitter.GetFollowingTimeline()); response.body = Encoding.UTF8.GetBytes(json); } else { string json = JsonConvert.SerializeObject(twitter.GetUserTimeline()); response.body = Encoding.UTF8.GetBytes(json); } } catch (Exception) { response.status = 404; response.body = Encoding.UTF8.GetBytes("404 User not found"); } } if (request.Method == "POST") { try { twitter.PostTweet(message); response.body = Encoding.UTF8.GetBytes("200 OK"); } catch (Exception) { response.status = 404; response.body = Encoding.UTF8.GetBytes("404 User not found"); } } } response.type = "application/json"; return(response); }
public HTTPResponse GetResponse(HTTPRequest request) { HTTPResponse response = new HTTPResponse(200); StringBuilder sb = new StringBuilder(); Dictionary <String, String> parameters = new Dictionary <string, string>(); sb.Append("<h1>OX Game</h1>"); String[] parts = Regex.Split(request.Filename, "[?]"); if (parts.Length > 1) { // http://stackoverflow.com/a/4982122 parameters = parts[1].Split('&').Select(x => x.Split('=')).ToDictionary(x => x[0].ToLower(), x => x[1]); } if (!parameters.ContainsKey("action")) // No action? go to Homepage { // show login screen if (!parameters.ContainsKey("username")) { sb.Append("<h2>Login</h2>"); sb.Append("<form method=\"get\">"); sb.Append("Username: <input type=\"text\" name=\"username\" value=\"\" /> <br />"); sb.Append("Password: <input type=\"password\" name=\"password\" value=\"\" /> <br />"); sb.Append("<input type=\"submit\" name=\"action\" value=\"Login\" /> <br />"); sb.Append("</form>"); } else { sb.Append(String.Format("<h2>Wellcome {0}</h2>", parameters["username"])); } // Show player list sb.Append("<h2>Player's List</h2>"); sb.Append("<table border=\"1\"><tr><td>Name</td><td>Win</td><td>Loss</td><td>Draw</td></tr>"); foreach (Player player in _playerList) { sb.Append(String.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>", player.Name, player.WinNum, player.LostNum, player.DrawNum)); } sb.Append("</table>"); sb.Append("<a href=\"/ox?action=newplayer\">Create new player</a>"); // Show game list sb.Append("<h2>Game's List</h2>"); sb.Append("<table border=\"1\"><tr><td>Game #</td><td>X</td><td>O</td><td>Action</td></tr>"); foreach (Game game in _gameList) { String xPlayer = (game.XPlayer != null) ? game.XPlayer.Name : "--"; String oPlayer = (game.OPlayer != null) ? game.OPlayer.Name : "--"; sb.Append(String.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td>", game.Index, xPlayer, oPlayer)); if (parameters.ContainsKey("username") && (game.Status == Game.CONT || game.Status == Game.CREATED_O || game.Status == Game.CREATED_X)) { if (parameters["username"] == xPlayer || parameters["username"] == oPlayer) { if (game.Status == Game.CREATED_O || game.Status == Game.CREATED_X) { sb.Append("<td>Wait</td>"); } else { sb.Append(String.Format("<td><a href=\"/ox?action=playgame&game={0}&username={1}\">Play</a>", game.Index, parameters["username"])); } } else { sb.Append(String.Format("<td><a href=\"/ox?action=joingame&game={0}&username={1}\">Join</a>", game.Index, parameters["username"])); } } else { if (game.Status == Game.X_WIN) { sb.Append("<td>X Win</td>"); } else if (game.Status == Game.O_WIN) { sb.Append("<td>O Win</td>"); } else if (game.Status == Game.DRAW) { sb.Append("<td>Draw</td>"); } else if (game.Status != Game.CONT) { sb.Append("<td>WAITING</td>"); } } } sb.Append("</tr></table>"); if (parameters.ContainsKey("username")) { sb.Append(String.Format("<a href=\"/ox?action=startgame&username={0}\">Start new game</a><br />", parameters["username"])); } } else //Action page { if (parameters["action"] == "newplayer") // create new player page { sb.Append("<h2>Create new player</h2>"); sb.Append("<form method=\"get\">"); sb.Append("Username: <input type=\"text\" name=\"username\" value=\"\" /> <br />"); sb.Append("Password: <input type=\"text\" name=\"password\" value=\"\" /> <br />"); sb.Append("<input type=\"hidden\" name=\"action\" value=\"addnewplayer\" /> <br />"); sb.Append("<input type=\"submit\" name=\"submit\" value=\"Login\" /> <br />"); sb.Append("</form>"); } else if (parameters["action"] == "addnewplayer") // create new player logic { if (parameters.ContainsKey("username") && parameters["username"] != "" && parameters.ContainsKey("password") && parameters["password"] != "") { AddPlayer(parameters["username"].Trim(), parameters["password"].Trim()); sb.Append("<h2>Player added successfully</h2>"); sb.Append(String.Format("Please note your login is <b>{0}</b> and password is <b>{1}</b>. <br />", parameters["username"], parameters["password"])); sb.Append(String.Format("<a href=\"/ox?username={0}\">Click here to go back to home page</a>", parameters["username"])); } else { sb.Append("<h2>Error: Username/password are missing</h2>"); sb.Append("<a href=\"/ox\">Click here to go back to home page</a>"); } } else if (parameters["action"] == "Login") { Boolean succ = false; if (parameters.ContainsKey("username") && parameters["username"] != "" && parameters.ContainsKey("password") && parameters["password"] != "") { foreach (Player player in _playerList) { if (succ = player.Login(parameters["username"], parameters["password"])) { break; } } if (succ) { sb.Append("<h2>Login successfully</h2>"); sb.Append(String.Format("<a href=\"/ox?action=startgame&username={0}\">Start new game</a><br /><br />", parameters["username"])); sb.Append(String.Format("<a href=\"/ox?username={0}\">Click here to go back to home page.</a>", parameters["username"])); } else { sb.Append("<h2>Error: Incorrect Username/password</h2>"); sb.Append("<a href=\"/ox\">Click here to go back to home page</a>"); } } else { sb.Append("<h2>Error: Username/password are missing</h2>"); sb.Append("<a href=\"/ox\">Click here to go back to home page</a>"); } } else if (parameters["action"] == "startgame") // create new game { sb.Append("<h2>Start new game</h2>"); sb.Append(String.Format("Choose side: <a href=\"/ox?action=chooseside&side=x&username={0}\">X</a> or <a href=\"/ox?action=chooseside&side=x&username={0}\">O</a>?<br /><br />", parameters["username"])); sb.Append(String.Format("<a href=\"/ox?username={0}\">Click here to go back to home page.</a>", parameters["username"])); } else if (parameters["action"] == "chooseside") { int id; Player player = GetPlayerByUserName(parameters["username"]); if (player == null) { sb.Append(String.Format("<h2>Error, user {0} not found</h2>", parameters["username"])); sb.Append("<a href=\"/ox\">Click here to go back to home page (you will need to login again)</a>"); } else { if (parameters["side"] == "x") // choose to play as X { id = NewGame(player, null); Game game = GetGameByID(id); game.Status = Game.CREATED_X; } else { id = NewGame(player, null); Game game = GetGameByID(id); game.Status = Game.CREATED_O; } sb.Append(String.Format("<h2>Start new game by {0} as {1}. The game ID is {2}.</h2>", parameters["username"], parameters["side"], id)); sb.Append("You will need to wait for another player to join the game.<br /><br />"); sb.Append(String.Format("<a href=\"/ox?username={0}\">Click here to go back to home page.</a>", parameters["username"])); } } else if (parameters["action"] == "joingame") { int id = Int16.Parse(parameters["game"]); Game game = GetGameByID(id); if (game.Status == Game.CREATED_X || game.Status == Game.CREATED_O) { if (game.Status == Game.CREATED_X) { game.OPlayer = GetPlayerByUserName(parameters["username"]); } else { game.XPlayer = GetPlayerByUserName(parameters["username"]); } game.Status = Game.CONT; sb.Append("<h2>Game is started</h2>"); sb.Append(String.Format("<a href=\"/ox?action=playgame&username={0}&game={1}\">Click here to go to your game</a><br /><br />", parameters["username"], id)); sb.Append(String.Format("<a href=\"/ox?username={0}\">Click here to go back to home page.</a>", parameters["username"])); } else { sb.Append("<h2>Error: can't join the game</h2> Game is either finished or someone already joins the game. Please go back to home page to join the other games or start a new one."); sb.Append(String.Format("<a href=\"/ox?username={0}\">Click here to go back to home page.</a>", parameters["username"])); } } else if (parameters["action"] == "playgame") { Game game = GetGameByID(Int16.Parse(parameters["game"])); char myPlayer; char gameStatus = Game.CONT; if (game == null) { sb.Append("<h2>Error: game doesn't exists, start one at home page."); sb.Append(String.Format("<a href=\"/ox?username={0}\">Click here to go back to home page.</a>", parameters["username"])); } else { if (parameters["username"] == game.XPlayer.Name) { sb.Append(String.Format("<h2>Game {0} between X:<u>{1}</u> and O:{2}</h2>", parameters["game"], game.XPlayer.Name, game.OPlayer.Name)); } else { sb.Append(String.Format("<h2>Game {0} between X:{1} and O:<u>{2}</u></h2>", parameters["game"], game.XPlayer.Name, game.OPlayer.Name)); } if (game.XPlayer.Name == parameters["username"]) { myPlayer = OXBoard.X_PLAYER; } else { myPlayer = OXBoard.O_PLAYER; } if (parameters.ContainsKey("row") && parameters.ContainsKey("col")) // User wants to play { gameStatus = game.Turn(Int16.Parse(parameters["row"]), Int16.Parse(parameters["col"])); } if (game.Status == Game.X_WIN) { sb.Append("<h2>X WIN!!!</h2>"); } else if (game.Status == Game.O_WIN) { sb.Append("<h2>O WIN!!!</h2>"); } else if (game.Status == Game.DRAW) { sb.Append("<h2>Draw</h2>"); } else // Game is not finished yet { char[,] board = game.Board.Board; char currentPlayer = game.Player; String playLink; if (currentPlayer == myPlayer) { playLink = String.Format("/ox?action=playgame&game={0}&username={1}&side={2}", parameters["game"], parameters["username"], currentPlayer); } else { playLink = ""; sb.Append("It's not your turn, please wait for your turn. You might need to reload the page."); } sb.Append("<table border=\"1\">"); for (int row = 0; row != 3; row++) { sb.Append("<tr>"); for (int col = 0; col != 3; col++) { sb.Append("<td>"); if (board[row, col] == OXBoard.X_PLAYER) { sb.Append(OXBoard.X_PLAYER); } else if (board[row, col] == OXBoard.O_PLAYER) { sb.Append(OXBoard.O_PLAYER); } else { if (playLink != "") { sb.Append(String.Format("<a href=\"{0}&row={1}&col={2}\">?</a>", playLink, row, col)); } else { sb.Append(" "); } } sb.Append("</td>"); } sb.Append("</tr>"); } sb.Append("</table>"); } sb.Append(String.Format("<a href=\"/ox?username={0}\">Click here to go back to home page.</a><br><br>", parameters["username"])); sb.Append(String.Format("<a href=\"/ox?action=surrender&game={0}&username={1}\">Surrender</a>", game.Index, parameters["username"])); } } else if (parameters["action"] == "surrender") { Game game = GetGameByID(Int16.Parse(parameters["game"])); if (game.XPlayer.Name == parameters["username"]) { game.Status = 'o'; } else { game.Status = 'x'; } if (game.Status == Game.X_WIN) { sb.Append("<h2>X WIN!!!</h2>"); } else if (game.Status == Game.O_WIN) { sb.Append("<h2>O WIN!!!</h2>"); } else if (game.Status == Game.DRAW) { sb.Append("<h2>Draw</h2>"); } sb.Append(String.Format("<a href=\"/ox?username={0}\">Click here to go back to home page.</a><br><br>", parameters["username"])); } } response.body = Encoding.UTF8.GetBytes(sb.ToString()); return(response); }
/// <summary> /// Get a request from client, process it, then return response to client /// </summary> public void Process() { NetworkStream ns = new NetworkStream(_client); string requestStr = ""; HTTPRequest request = null; HTTPResponse response = null; byte[] bytes = new byte[1024]; int bytesRead; // Read all request do { bytesRead = ns.Read(bytes, 0, bytes.Length); requestStr += Encoding.UTF8.GetString(bytes, 0, bytesRead); } while (ns.DataAvailable); request = new HTTPRequest(requestStr); request.addProperty("RemoteEndPoint", _client.RemoteEndPoint.ToString()); // We can handle only GET now if (request.Status != 200) { response = new HTTPResponse(request.Status); } else { bool processed = false; // pre processing foreach (KeyValuePair <string, PluginInfo> plugininfo in plugins) { if (plugininfo.Value.preprocessing) { plugininfo.Value.reference.PreProcessing(request); } } // plugins foreach (KeyValuePair <string, PluginInfo> plugininfo in plugins) { if (request.Filename.StartsWith(plugininfo.Key)) { response = plugininfo.Value.reference.GetResponse(request); processed = true; } } // local file if (!processed) { if (request.Filename.Equals("")) { response = getFile(ROOT + "/index.html"); } else { response = getFile(ROOT + "/" + request.Filename); } } // post processing pipe foreach (KeyValuePair <string, PluginInfo> plugininfo in plugins) { if (plugininfo.Value.postprocessing) { response = plugininfo.Value.reference.PostProcessing(response); } } } // Generate response ns.Write(Encoding.UTF8.GetBytes(response.header), 0, response.header.Length); if (response.body != null) { ns.Write(response.body, 0, response.body.Length); } // Shuting down //ns.Close(); _client.Shutdown(SocketShutdown.Both); //_client.Close(); }
/// <summary> /// Get a request from client, process it, then return response to client /// </summary> public void Process() { NetworkStream ns = new NetworkStream(_client); StringBuilder requestStr = new StringBuilder(); HTTPRequest request = null; HTTPResponse response = null; byte[] bytes = new byte[1024]; int bytesRead; // Read all request do { bytesRead = ns.Read(bytes, 0, bytes.Length); requestStr.Append(Encoding.UTF8.GetString(bytes, 0, bytesRead)); } while (ns.DataAvailable); request = new HTTPRequest(requestStr.ToString()); request.AddProperty("RemoteEndPoint", _client.RemoteEndPoint.ToString()); // We can handle only GET now if (request.Status != 200) { response = new HTTPResponse(request.Status); } else { bool processed = false; //FIXME, this seem duplicate with HTTPRequest string[] requestUrls = request.Url.Split("/"); string[] paths = requestUrls[1].Split("?"); // pre processing foreach (KeyValuePair <string, PluginInfo> plugininfo in PM.Plugins) { if (plugininfo.Value.preprocessing) { plugininfo.Value.reference.PreProcessing(request); } } // plugins foreach (KeyValuePair <string, PluginInfo> plugininfo in PM.Plugins) { if (paths[0].Equals(plugininfo.Key, StringComparison.InvariantCultureIgnoreCase)) { //if(request.Url.StartsWith("/" + plugininfo.Key)) { response = plugininfo.Value.reference.GetResponse(request); processed = true; } } // local file if (!processed) { if (request.Filename.Equals("")) { response = getFile(ROOT + "/" + request.Url + "/index.html"); } else { response = getFile(ROOT + "/" + request.Url); } } // post processing pipe foreach (KeyValuePair <string, PluginInfo> plugininfo in PM.Plugins) { if (plugininfo.Value.postprocessing) { response = plugininfo.Value.reference.PostProcessing(response); } } } // Generate response ns.Write(Encoding.UTF8.GetBytes(response.Header), 0, response.Header.Length); if (response.Body != null) { ns.Write(response.Body, 0, response.Body.Length); } // Shuting down //ns.Close(); _client.Shutdown(SocketShutdown.Both); //_client.Close(); }
public virtual HTTPResponse GetResponse(HTTPRequest request) { HTTPResponse response = new HTTPResponse(200); StringBuilder sb = new StringBuilder(); string user = request.getRequestByKey("user"); string password = request.getRequestByKey("password"); string action = request.getRequestByKey("action"); string following = request.getRequestByKey("following"); string message = request.getRequestByKey("message"); if (user == null) // no user? show login screen { sb.Append("<h1>Twitter</h1>"); sb = GenLoginPage(sb); } else { if (action == null) // No action? go to homepage { try { Twitter twitter = new Twitter(user); sb.Append(String.Format("<h1>{0}'s Twitter</h1>", user)); sb = GenTimeline(twitter, sb); } catch (Exception ex) { sb.Append(String.Format("Error [{0}], please go back to <a href=\"/twitter\">login page</a> to try again", ex.Message)); } } else { if (action.Equals("newuser")) { if (user != null && password != null && user != "" && password != "") { try { Twitter.AddUser(user, password); sb.Append("User added successfully, please go back to <a href=\"/twitter\">login page</a> to login"); } catch (Exception ex) { sb.Append(String.Format("Error adding user with error [{0}], please go back to <a href=\"/twitter\">login page</a> to try again", ex.Message)); } } } else if (action.Equals("login")) { if (user != null && password != null && user != "" && password != "") { if (Twitter.IsValidUser(user, password)) { sb.Append(String.Format("Welcome {0}, please go back to <a href=\"/twitter?user={0}\">tweet page</a> to begin", user)); } else { sb.Append("Error login, please go back to <a href=\"/twitter\">login page</a> to try again"); } } } else { Twitter twitter = new Twitter(user); sb.Append(String.Format("<h1>{0}'s Twitter</h1>", user)); if (action.Equals("following")) { try { twitter.AddFollowing(following); sb = GenTimeline(twitter, sb); } catch (Exception ex) { sb.Append(String.Format("Error [{0}], please go back to <a href=\"/twitter\">login page</a> to try again", ex.Message)); } } else if (action.Equals("tweet")) { try { twitter.PostTweet(message); sb = GenTimeline(twitter, sb); } catch (Exception ex) { Console.WriteLine(ex.ToString()); sb.Append(String.Format("Error [{0}], please go back to <a href=\"/twitter\">login page</a> to try again", ex.Message)); } } } } } response.body = Encoding.UTF8.GetBytes(sb.ToString()); return(response); }
public new HTTPResponse GetResponse(HTTPRequest request) { HTTPResponse response = new HTTPResponse(200); StringBuilder sb = new StringBuilder(); session = request.GetPropertyByKey("X-session"); string[] urlToken = request.Url.Split("/"); if (urlToken.Length > 2) { action = urlToken[2]; } else { action = null; } requestMethod = request.Method; string username = request.GetRequestByKey("username"); string password = request.GetRequestByKey("password"); if (IsMethod(HTTP_OPTIONS)) { return(response); } if (IsAction(USER_ACTION)) { if (IsMethod(HTTP_POST)) { if (!IsNOE(username) && !IsNOE(password)) { try { Twitter.AddUser(username, password); response.Status = 201; } catch (Exception ex) { response.SetBody(ex.Message); response.Status = 500; } } else { response.SetBody("Username and password required"); response.Status = 400; return(response); } } } else if (IsAction(LOGIN_ACTION)) { if (IsMethod(HTTP_POST)) { if (!IsNOE(username) && !IsNOE(password)) { if (Twitter.IsValidUser(username, password)) { string newSession = Twitter.GenSession(username); if (!IsNOE(newSession)) { response.Status = 201; dynamic jobj = new JObject(); jobj.Session = newSession; response.Type = "application/json"; string resp = JsonConvert.SerializeObject(jobj); response.Body = Encoding.UTF8.GetBytes(resp); return(response); } response.SetBody("Can't create session"); response.Status = 500; return(response); } else { response.SetBody("Invalid username/password"); response.Status = 404; return(response); } } else { response.SetBody("Username and password required"); response.Status = 400; return(response); } } } else if (!IsNOE(session)) { User user = Twitter.GetUserFromSession(session); if (user == null) { response.SetBody("User not found, please login again"); response.Status = 404; return(response); } Twitter twitter = new Twitter(user.Name); if (IsNOE(action)) { if (IsMethod(HTTP_GET)) { try { response = new HTTPResponse(200); response.Type = "application/json"; string resp = JsonConvert.SerializeObject(twitter.GetFollowingTimeline()); if (IsNOE(resp)) { response.SetBody("No post in timline"); response.Status = 404; return(response); } response.Body = Encoding.UTF8.GetBytes(resp); return(response); } catch (Exception ex) { response.SetBody(ex.Message); response.Status = 500; return(response); } } } else if (IsAction(LOGOUT_ACTION)) { if (IsMethod(HTTP_POST)) { try { Twitter.RemoveSession(user.Name); response.Status = 200; return(response); } catch (Exception ex) { response.SetBody(ex.Message); response.Status = 500; return(response); } } } else if (IsAction(TWEET_ACTION)) { if (IsMethod(HTTP_GET)) { try { response = new HTTPResponse(200); response.Type = "application/json"; string resp = null; if (IsNOE(urlToken[3])) { resp = JsonConvert.SerializeObject(twitter.GetTimeline(user)); } else { User aUser = Twitter.GetUserFromName(urlToken[3]); if (aUser == null) { response.SetBody("User not found"); response.Status = 404; return(response); } resp = JsonConvert.SerializeObject(twitter.GetTimeline(aUser)); } if (IsNOE(resp)) { response.SetBody("No post in timline"); response.Status = 404; return(response); } response.Body = Encoding.UTF8.GetBytes(resp); return(response); } catch (Exception ex) { response.SetBody(ex.Message); response.Status = 500; return(response); } } else if (IsMethod(HTTP_POST)) { try { string message = request.GetRequestByKey("message"); if (IsNOE(message)) { response.SetBody("Message required"); response.Status = 400; return(response); } Tweet tweet = new Tweet(); tweet.User = user.Name; tweet.Message = message; tweet.DateCreated = DateTime.Now; using (var context = new TweetContext()) { context.Tweets.Add(tweet); context.SaveChanges(); } response.Status = 201; return(response); } catch (Exception ex) { response.SetBody(ex.Message); response.Status = 500; return(response); } } else if (IsMethod(HTTP_DELETE)) { try { throw (new NotImplementedException()); } catch (Exception ex) { response.SetBody(ex.Message); response.Status = 501; return(response); } } } else if (IsAction(FOLLOWING_ACTION)) { if (IsMethod(HTTP_GET)) { response = new HTTPResponse(200); response.Type = "application/json"; string resp = JsonConvert.SerializeObject(user.Following); if (resp == null) { response.SetBody("No following"); response.Status = 404; return(response); } response.Body = Encoding.UTF8.GetBytes(resp); return(response); } else if (IsMethod(HTTP_POST)) { string following = request.GetRequestByKey("followingname"); try { twitter.AddFollowing(following); response = new HTTPResponse(201); response.Type = "application/json"; string resp = JsonConvert.SerializeObject(user.Following); if (resp == null) { response.SetBody("No folowing"); response.Status = 404; return(response); } response.Body = Encoding.UTF8.GetBytes(resp); return(response); } catch (Exception ex) { response.Status = 400; response.SetBody(ex.Message); return(response); } } else if (IsMethod(HTTP_DELETE)) { string following = request.GetRequestByKey("followingname"); try { twitter.RemoveFollowing(following); response = new HTTPResponse(200); response.Type = "application/json"; string resp = JsonConvert.SerializeObject(user.Following); if (resp == null) { response.SetBody("No following"); response.Status = 404; return(response); } response.Body = Encoding.UTF8.GetBytes(resp); return(response); } catch (Exception ex) { response.Status = 400; response.SetBody(ex.Message); return(response); } } } } response.Status = 400; return(response); }
public override HTTPResponse GetResponse(HTTPRequest request) { HTTPResponse response = null; StringBuilder sb = new StringBuilder(); string[] path = request.Filename.Split("?"); if (path[0].ToLower() == "user") { if (request.Status == 200) { if (request.Method.ToLower() == "get")//GET { try{ response = new HTTPResponse(200); response.type = "json"; response.body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(GetListUser())); //get list user }catch (Exception) { response = new HTTPResponse(400); } } else if (request.Method.ToLower() == "post") //POST { try{ Twitter.AddUser(request.getRequestByKey("user").ToLower(), request.getRequestByKey("password").ToLower());//add user sb.Append("<html><head><title>TwitterAPI</title></head><body>"); sb.Append("Added User : "******"user").ToLower() + " Complete!"); sb.Append("</body></html"); response = new HTTPResponse(200); response.body = Encoding.UTF8.GetBytes(sb.ToString()); }catch (Exception) { response = new HTTPResponse(400); } } else if (request.Method.ToLower() == "delete") //DELETE { try{ Twitter t = new Twitter(request.getRequestByKey("user")); t.DeleteUser(request.getRequestByKey("user")); sb.Append("<html><head><title>TwitterAPI</title></head><body>"); sb.Append("Delete User : "******"user").ToLower() + " Complete!"); sb.Append("</body></html"); response = new HTTPResponse(200); response.body = Encoding.UTF8.GetBytes(sb.ToString()); }catch (Exception) { response = new HTTPResponse(400); } } else //OTHER ELSE { response = new HTTPResponse(400); } } else { response = new HTTPResponse(400); } } else if (path[0].ToLower() == "following") { if (request.Status == 200) { if (request.Method.ToLower() == "get") { try{ response = new HTTPResponse(200); response.type = "json"; response.body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(GetListFollowing(request.getRequestByKey("user")))); //get following user }catch (Exception) { response = new HTTPResponse(400); } } else if (request.Method.ToLower() == "post") { try { Twitter t = new Twitter(request.getRequestByKey("user")); t.AddFollowing(request.getRequestByKey("follow")); sb.Append("<html><head><title>TwitterAPI</title></head><body>"); sb.Append("User : "******"user").ToLower() + " Start Following : " + request.getRequestByKey("follow") + " Complete!"); sb.Append("</body></html"); response = new HTTPResponse(200); response.body = Encoding.UTF8.GetBytes(sb.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); response = new HTTPResponse(400); } } else if (request.Method.ToLower() == "delete") { try { Twitter t = new Twitter(request.getRequestByKey("user")); t.RemoveFollowing(request.getRequestByKey("follow")); sb.Append("<html><head><title>TwitterAPI</title></head><body>"); sb.Append("User : "******"user").ToLower() + " Unfollowing : " + request.getRequestByKey("follow") + " Complete!"); sb.Append("</body></html"); response = new HTTPResponse(200); response.body = Encoding.UTF8.GetBytes(sb.ToString()); } catch (Exception) { response = new HTTPResponse(400); } } else { response = new HTTPResponse(400); } } else { response = new HTTPResponse(400); } } else if (path[0].ToLower() == "tweet") { if (request.Status == 200) { if (request.Method.ToLower() == "get") { if (request.getRequestByKey("getlist").ToLower() == "user") { try { Twitter t = new Twitter(request.getRequestByKey("user")); response = new HTTPResponse(200); response.type = "json"; response.body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(t.GetUserTimeline())); } catch (Exception) { response = new HTTPResponse(400); } } else if (request.getRequestByKey("getlist").ToLower() == "following") { try { Twitter t = new Twitter(request.getRequestByKey("user")); response = new HTTPResponse(200); response.type = "json"; response.body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(t.GetFollowingTimeline())); } catch (Exception ex) { Console.Write(ex.ToString()); response = new HTTPResponse(400); } } else { response = new HTTPResponse(400); } } else if (request.Method.ToLower() == "post") { try { Twitter t = new Twitter(request.getRequestByKey("user")); t.PostTweet(request.getRequestByKey("tweet")); sb.Append("<html><head><title>TwitterAPI</title></head><body>"); sb.Append("User : "******"user").ToLower() + " Tweet : " + request.getRequestByKey("tweet")); sb.Append("</body></html"); response = new HTTPResponse(200); response.body = Encoding.UTF8.GetBytes(sb.ToString()); } catch (Exception) { response = new HTTPResponse(400); } } else { response = new HTTPResponse(400); } } else { response = new HTTPResponse(400); } } else { sb.Append("<html><head><title>TwitterAPI</title></head><body>"); sb.Append("<h1>TwitterAPI</h1>"); sb.Append("</body></html"); response = new HTTPResponse(200); response.body = Encoding.UTF8.GetBytes(sb.ToString()); } return(response); }
public override HTTPResponse GetResponse(HTTPRequest request) { HTTPResponse response = new HTTPResponse(200); string user = request.getRequestByKey("user"); string password = request.getRequestByKey("password"); string following = request.getRequestByKey("follow"); string message = request.getRequestByKey("message"); string time = request.getRequestByKey("timeline"); string[] name = request.Filename.Split("?"); //split part if (name[0] == "API") { Twitter twitter = new Twitter(user); if (request.Method == "GET") { string json = JsonConvert.SerializeObject(ListUsers()); //show list user response.body = Encoding.UTF8.GetBytes(json); } else if (request.Method == "POST") { try { Twitter.AddUser(user, password); //add usersby use name and password. response.body = Encoding.UTF8.GetBytes("SUCCESS"); } catch (Exception) { response.status = 403; response.body = Encoding.UTF8.GetBytes("ERROR"); } } else if (request.Method == "DELETE") { try { twitter.RemoveUser(user); //remove user by use name but sill bug if user have following it can not delete. response.body = Encoding.UTF8.GetBytes("OK^_^"); } catch (Exception) { response.body = Encoding.UTF8.GetBytes("DELETE ERROR"); } } } else if (name[0] == "FOLLOW") { Twitter twitter = new Twitter(user); if (request.Method == "GET") { string json = JsonConvert.SerializeObject(ListFollow(user)); //list all following. response.body = Encoding.UTF8.GetBytes(json); } else if (request.Method == "POST") { try { if (twitter.chack(following)) //chack it have follow in list if not add it. { Twitter Friend = new Twitter(user); Friend.AddFollowing(following); //AddFollowing response.body = Encoding.UTF8.GetBytes("SUCCESS"); } } catch (Exception) { response.status = 403; response.body = Encoding.UTF8.GetBytes("ERROR"); } } else if (request.Method == "DELETE") { try { twitter.RemoveFollowing(following); //RemoveFollowing. response.body = Encoding.UTF8.GetBytes("OK^_^"); } catch (Exception) { response.body = Encoding.UTF8.GetBytes("DELETE ERROR"); } } } else if (name[0] == "TWEET") { Twitter twitter = new Twitter(user); if (request.Method == "GET") { if (time == "FOLLOW") { string json = JsonConvert.SerializeObject(twitter.GetFollowingTimeline()); //get timeline Following if FOLLOW response.body = Encoding.UTF8.GetBytes(json); } else { string json = JsonConvert.SerializeObject(twitter.GetFollowingTimeline()); //get timeline Following response.body = Encoding.UTF8.GetBytes(json); } } else if (request.Method == "POST") { try { twitter.PostTweet(message); //POst message response.body = Encoding.UTF8.GetBytes("SUCCESS"); } catch (Exception) { response.status = 403; response.body = Encoding.UTF8.GetBytes("ERROR"); } } else if (request.Method == "DELETE") { try { response.body = Encoding.UTF8.GetBytes("OK^_^"); } catch (Exception) { response.body = Encoding.UTF8.GetBytes("DELETE ERROR"); } } } response.type = "application/json"; return(response); }