public static async Task StoreMessage(string sender, string receiver, string message) { string pmKeyTag = KeyTagID.GetPMKeyTag(sender, receiver); string time = GlobalVar.currentDate(); using (NpgsqlConnection connection = new NpgsqlConnection(Network.NpgSQLConnection)) { connection.Open(); NpgsqlCommand insertPMCommand = null; try { insertPMCommand = new NpgsqlCommand("INSERT INTO embyrprivatemessages." + pmKeyTag + " (message, username, time) values(:message, :username, :time)", connection); insertPMCommand.Parameters.Add(new NpgsqlParameter(":message", message)); insertPMCommand.Parameters.Add(new NpgsqlParameter(":username", sender)); insertPMCommand.Parameters.Add(new NpgsqlParameter(":time", time)); NpgsqlDataReader dataReader = await insertPMCommand.ExecuteReaderAsync(); await dataReader.ReadAsync(); } catch (NpgsqlException e) { Console.WriteLine(e.ToString()); } connection.Close(); } }
public static Tuple <string[], string[], string[]> StartupLoadMessages(string senderName, string receiverName, int n) { try { string[] message = new string[0]; string[] sender = new string[0]; string[] time = new string[0]; string pmKeyTag = KeyTagID.GetPMKeyTag(senderName, receiverName); NpgsqlConnection connMsg = new NpgsqlConnection(Network.NpgSQLConnection); connMsg.Open(); NpgsqlCommand getMessagesCountCommand = new NpgsqlCommand("SELECT count(*) FROM embyrprivatemessages." + pmKeyTag, connMsg); Int64 msgCnt = (Int64)getMessagesCountCommand.ExecuteScalar(); connMsg.Close(); if (msgCnt != n || msgCnt == 0) { if (n != 0) { msgCnt = msgCnt - n; } if (msgCnt >= 15) { message = new string[15]; sender = new string[15]; time = new string[15]; } else { message = new string[msgCnt]; sender = new string[msgCnt]; time = new string[msgCnt]; } try { using (NpgsqlConnection conn = new NpgsqlConnection(Network.NpgSQLConnection)) { conn.Open(); NpgsqlCommand getMessagesCommand = new NpgsqlCommand("SELECT * FROM(SELECT message, username, time, ROW_NUMBER() OVER(ORDER BY time) FROM embyrprivatemessages." + pmKeyTag + ") x WHERE ROW_NUMBER BETWEEN " + (msgCnt - 14).ToString() + " AND " + msgCnt.ToString(), conn); NpgsqlDataReader getMessagesReader = getMessagesCommand.ExecuteReader(); int i = 0; while (getMessagesReader.Read()) { message[i] = getMessagesReader[0].ToString(); sender[i] = getMessagesReader[1].ToString(); time[i] = getMessagesReader[2].ToString().Substring(0, 14) + DateTime.Parse(getMessagesReader[2].ToString().Remove(14, 1).Substring(14)).ToString(@" h\:mm tt"); if (i < message.Length - 1) { i++; } } getMessagesReader.Close(); var tuple = new Tuple <string[], string[], string[]>(message, sender, time); return(tuple); } } catch (NpgsqlException ex) { Console.WriteLine(ex.ToString()); return(null); } } return(new Tuple <string[], string[], string[]>(message, sender, time)); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(null); } }
public async Task InvokeAsync(HttpContext context) { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); bool clientEstablished = false; await Receive(webSocket, async (result, buffer) => { if (clientEstablished == false && result.MessageType == WebSocketMessageType.Text) { _manager.AddSocket(Encoding.UTF8.GetString(buffer, 0, result.Count), webSocket); clientEstablished = true; string username = Encoding.UTF8.GetString(buffer, 0, result.Count); await webSocket.SendAsync(Encoding.UTF8.GetBytes("{\"eventV\": \"setProfilePhoto\", \"user\": \"" + username + "\", \"photoBytes\": \"" + ProfilePhoto.GetImage(username) + "\"}"), WebSocketMessageType.Text, true, CancellationToken.None); FriendsList.SetOnline(username, "true"); List <string> obj = new List <string>() { username, FriendsList.GetStatus(username) }; List <string> friends = FriendsList.GetFriends(username).Split(GlobalVar.delimiterChars, System.StringSplitOptions.RemoveEmptyEntries).OfType <string>().ToList(); foreach (string friend in friends) { await RouteJSONMessageAsync("setStatus", obj, friend); try { await webSocket.SendAsync(Encoding.UTF8.GetBytes("{\"eventV\": \"setProfilePhoto\", \"user\": \"" + friend + "\", \"photoBytes\": \"" + ProfilePhoto.GetImage(friend) + "\"}"), WebSocketMessageType.Text, true, CancellationToken.None); } catch { Console.WriteLine("Error Loading {0}'s Profile Photo!", friend); } } Console.WriteLine($"WebSocket Operation: Client->EstablishedConnection"); Console.WriteLine("\nSet the status of: {0}\tChanged to: online", obj[0]); } else { if (result.MessageType == WebSocketMessageType.Text) { List <string> obj = new List <string>(); dynamic jsonObj = JObject.Parse(Encoding.UTF8.GetString(buffer, 0, result.Count)); string job = jsonObj.job; switch (job) { case ("sendMessage"): obj.Add((jsonObj.message).ToString()); obj.Add((jsonObj.sender).ToString()); obj.Add((jsonObj.receiver).ToString()); obj.Add(GlobalVar.currentDateMsg()); obj.Add((jsonObj.ghostMode).ToString()); Console.WriteLine(obj[4].ToString()); Console.WriteLine("Operation:\tsendMessage\n"); await RouteJSONMessageAsync(job, obj, obj[2]); break; case ("setStatus"): obj.Add((jsonObj.sender).ToString()); obj.Add((jsonObj.status).ToString()); Console.WriteLine("Operation:\tsetStatus\n"); List <string> friends = FriendsList.GetFriends(obj[0]).Split(GlobalVar.delimiterChars, System.StringSplitOptions.RemoveEmptyEntries).OfType <string>().ToList(); foreach (string friend in friends) { await RouteJSONMessageAsync(job, obj, friend); } break; case ("addFriendReq"): obj.Add((jsonObj.sender).ToString()); obj.Add((jsonObj.receiver).ToString()); Console.WriteLine("Operation:\taddFriendReq\n"); if (KeyTagID.GetUserExists(obj[1])) { FriendsList flAFR = new FriendsList("ADDFR", obj[0], obj[1], KeyTagID.GrabUserKeyTag(obj[0])); await webSocket.SendAsync(Encoding.UTF8.GetBytes("{\"eventV\": \"userExists\", \"existsV\": true, \"user\": \"" + obj[1].ToString() + "\"}"), WebSocketMessageType.Text, true, CancellationToken.None); await RouteJSONMessageAsync(job, obj, obj[1]); } else { await webSocket.SendAsync(Encoding.UTF8.GetBytes("{\"eventV\": \"userExists\", \"existsV\": false}"), WebSocketMessageType.Text, true, CancellationToken.None); } break; case ("cancelFriendReq"): obj.Add((jsonObj.sender).ToString()); obj.Add((jsonObj.receiver).ToString()); Console.WriteLine("Operation:\tcancelFriendReq\n"); FriendsList flRFR = new FriendsList("REMOVEFR", obj[0], obj[1], KeyTagID.GrabUserKeyTag(obj[0])); await RouteJSONMessageAsync(job, obj, obj[1]); break; case ("acceptFriendReq"): obj.Add((jsonObj.sender).ToString()); obj.Add((jsonObj.receiver).ToString()); obj.Add(ProfilePhoto.GetImage(obj[0])); Console.WriteLine("Operation:\tacceptFriendReq\n"); FriendsList flACFR = new FriendsList("ACCEPTFR", obj[0], obj[1], KeyTagID.GrabUserKeyTag(obj[0])); await RouteJSONMessageAsync(job, obj, obj[1]); await webSocket.SendAsync(Encoding.UTF8.GetBytes("{\"eventV\": \"setProfilePhoto\", \"user\": \"" + obj[0] + "\", \"photoBytes\": \"" + ProfilePhoto.GetImage(obj[1]) + "\"}"), WebSocketMessageType.Text, true, CancellationToken.None); break; case ("declineFriendReq"): obj.Add((jsonObj.sender).ToString()); obj.Add((jsonObj.receiver).ToString()); Console.WriteLine("Operation:\tdeclineFriendReq\n"); FriendsList flDFR = new FriendsList("DECLINEFR", obj[0], obj[1], 0); await RouteJSONMessageAsync(job, obj, obj[1]); break; case ("removeFriend"): obj.Add((jsonObj.sender).ToString()); obj.Add((jsonObj.receiver).ToString()); Console.WriteLine("Operation:\removeFriend\n"); FriendsList flRF = new FriendsList("REMOVE", obj[0], obj[1], 0); await RouteJSONMessageAsync(job, obj, obj[1]); break; case ("setProfilePhoto"): obj.Add((jsonObj.sender).ToString()); obj.Add((jsonObj.photoBytes).ToString()); Console.WriteLine("Operation:\tsetProfilePhoto\n"); ProfilePhoto.SaveImage(obj[0], obj[1]); List <string> friendsPP = FriendsList.GetFriends(obj[0]).Split(GlobalVar.delimiterChars, System.StringSplitOptions.RemoveEmptyEntries).OfType <string>().ToList(); foreach (string friend in friendsPP) { await RouteJSONMessageAsync(job, obj, friend); } break; } obj.Clear(); } else if (result.MessageType == WebSocketMessageType.Close) { string id = _manager.GetAllSockets().FirstOrDefault(s => s.Value == webSocket).Key; _manager.GetAllSockets().TryRemove(id, out WebSocket sock); await sock.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); List <string> obj = new List <string>(); obj.Add(id); obj.Add("offline"); List <string> friends = FriendsList.GetFriends(obj[0]).Split(GlobalVar.delimiterChars, System.StringSplitOptions.RemoveEmptyEntries).OfType <string>().ToList(); foreach (string friend in friends) { await RouteJSONMessageAsync("setStatusOffline", obj, friend); } FriendsList.SetOnline(id, "false"); Console.WriteLine("\nSet the status of: {0}\tChanged to: {1}", obj[0], obj[1]); Console.WriteLine($"WebSocket Operation: Receive->Close"); } } requestCount++; Console.WriteLine("\nRequest #: " + requestCount + "\nManaged Connections: " + _manager.GetAllSockets().Count.ToString()); Console.WriteLine("\n\n" + GlobalVar.border + "\n"); return; }); } else { await _next(context); } }
public static bool CreateAccount(string request) { string[] postReqKV = request.Split(GlobalVar.delimiterChars, System.StringSplitOptions.RemoveEmptyEntries); string username = postReqKV[1]; string password = postReqKV[3]; string ipaddress = postReqKV[5]; string usernameEncrypt; string time = GlobalVar.currentDate(); if (!(KeyTagID.GetUserExists(username))) { try { Random rand = new Random(); int keytag = rand.Next(0, 10000); while (KeyTagID.CheckKeyTag(keytag) == true) { keytag = rand.Next(0, 10000); if (KeyTagID.CheckKeyTag(keytag) == true) { continue; } else { break; } } using (NpgsqlConnection signupConnection = new NpgsqlConnection(Network.NpgSQLConnection)) { signupConnection.Open(); NpgsqlCommand command = new NpgsqlCommand("INSERT INTO embyraccounts.accounts (keyid,accountname,password,datecreated,ipaddress) values(:keytag,:usernameEncrypt,:password,:datecreated,:ipaddress)", signupConnection); command.Parameters.Add(new NpgsqlParameter("@keytag", keytag)); Encrypt.encryptText = username; usernameEncrypt = Encrypt.GlobalVar; command.Parameters.Add(new NpgsqlParameter("@usernameEncrypt", usernameEncrypt)); Encrypt.encryptText = password; password = Encrypt.GlobalVar; command.Parameters.Add(new NpgsqlParameter("@password", password)); command.Parameters.Add(new NpgsqlParameter("@datecreated", time)); command.Parameters.Add(new NpgsqlParameter("@ipaddress", ipaddress)); NpgsqlDataReader dataReader = command.ExecuteReader(); dataReader.Close(); command.CommandText = "INSERT INTO embyrfriends.friends (keyid, accountname, friends, requestsin, requestsout, status, online) VALUES (:keytag, :username, '', '', '', 'online', 'false')"; command.Parameters.Add(new NpgsqlParameter("@keytag", keytag)); command.Parameters.Add(new NpgsqlParameter("@username", username)); command.ExecuteNonQuery(); command.CommandText = "INSERT INTO embyrusers.users (keyid, accountname) VALUES (:keytag, :username)"; command.Parameters.Add(new NpgsqlParameter("@keytag", keytag)); command.Parameters.Add(new NpgsqlParameter("@username", username)); command.ExecuteNonQuery(); signupConnection.Close(); try { string sourceFile = System.IO.Path.Combine(@"C:\Users\Michael\Desktop\HTTPServerHost\server\Profile Photos\", "default.txt"); string destFile = System.IO.Path.Combine(@"C:\Users\Michael\Desktop\HTTPServerHost\server\Profile Photos\", username + ".txt"); System.IO.File.Copy(sourceFile, destFile, true); } catch (Exception e) { Console.WriteLine(e.ToString()); } return(true); } } catch (Exception e) { Console.WriteLine(e.ToString()); return(false); } } else { return(false); } }