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);
            }
        }
Example #2
0
        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);
            }
        }