/// <summary>
 /// Gets the information of the connection
 /// </summary>
 /// <param name="websocket"></param>
 /// <param name="session"></param>
 /// <returns></returns>
 public static string GetConnectionInfo(this ManagedWebSocket websocket, Session session = null)
 {
     session = session ?? websocket.Get <Session>("Session");
     return($"- Account: {websocket.Get("AccountInfo", "Visitor")} - Session ID: {session?.SessionID ?? "Unknown"} - Device ID: {session?.DeviceID ?? "Unknown"} - Origin: {(websocket.Headers.TryGetValue("Origin", out var origin) ? origin : session?.AppOrigin ?? "Unknown")}" + "\r\n" +
            $"- App: {session?.AppName ?? "Unknown"} @ {session?.AppPlatform ?? "Unknown"} [{session?.AppAgent ?? "Unknown"}]" + "\r\n" +
            $"- Connection IP: {session?.IP ?? "Unknown"} - Location: {websocket.Get("LocationInfo", "Unknown")} - WebSocket: {websocket.ID} @ {websocket.RemoteEndPoint}");
 }
        /// <summary>
        /// Prepares the information of the connection
        /// </summary>
        /// <param name="websocket"></param>
        /// <param name="correlationID"></param>
        /// <param name="session"></param>
        /// <param name="cancellationToken"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        public static async Task PrepareConnectionInfoAsync(this ManagedWebSocket websocket, string correlationID = null, Session session = null, CancellationToken cancellationToken = default, Microsoft.Extensions.Logging.ILogger logger = null)
        {
            correlationID = correlationID ?? UtilityService.NewUUID;
            session       = session ?? websocket.Get <Session>("Session");
            var account = "Visitor";

            if (!string.IsNullOrWhiteSpace(session?.User?.ID))
            {
                try
                {
                    var json = await Router.GetService("Users").ProcessRequestAsync(new RequestInfo(session, "Users", "Profile", "GET")
                    {
                        CorrelationID = correlationID
                    }, cancellationToken).ConfigureAwait(false);

                    account = $"{json?.Get<string>("Name") ?? "Unknown"} ({session.User.ID})";
                }
                catch (Exception ex)
                {
                    account = $"Unknown ({session.User.ID})";
                    logger?.LogError($"Error occurred while fetching an account profile => {ex.Message}", ex);
                }
            }
            websocket.Set("AccountInfo", account);
            websocket.Set("LocationInfo", session != null ? await session.GetLocationAsync(correlationID, cancellationToken).ConfigureAwait(false) : "Unknown");
        }
Пример #3
0
        public void OnDisconnection(ManagedWebSocket ws)
        {
            Connection connection = ws.Get <Connection>("agar");

            Console.WriteLine($"DISCONNECTION FROM {connection.RemoteAddress}");
            connection.OnSocketClose(0, null);
            connections.Remove(connection);
            globalChat.Remove(connection);
        }
Пример #4
0
        public void OnData(ManagedWebSocket ws, WebSocketReceiveResult res, byte[] data)
        {
            Connection connection = ws.Get <Connection>("agar");

            if (res.MessageType != WebSocketMessageType.Binary)
            {
                connection.CloseSocket(1003, "Invalid message type");
            }
            connection.OnSocketMessage(data);
        }
Пример #5
0
        static async Task WhenMessageIsReceivedAsync(this ManagedWebSocket websocket, WebSocketReceiveResult result, byte[] data)
        {
            // receive continuous messages
            object message;

            if (!result.EndOfMessage)
            {
                websocket.Extra["Message"] = websocket.Extra.TryGetValue("Message", out message) ? (message as byte[]).Concat(data) : data;
                return;
            }

            // last message or single small message
            var stopwatch     = Stopwatch.StartNew();
            var correlationID = UtilityService.NewUUID;

            if (websocket.Extra.TryGetValue("Message", out message))
            {
                message = (message as byte[]).Concat(data);
                websocket.Extra.Remove("Message");
            }
            else
            {
                message = data;
            }

            // check message
            var requestMsg = result.MessageType.Equals(WebSocketMessageType.Text) ? (message as byte[]).GetString() : null;

            if (string.IsNullOrWhiteSpace(requestMsg))
            {
                return;
            }

            // wait for the initializing process is completed
            while ("Initializing".IsEquals(websocket.GetStatus()))
            {
                await Task.Delay(UtilityService.GetRandomNumber(123, 456), Global.CancellationTokenSource.Token).ConfigureAwait(false);
            }

            // check session
            var session = websocket.Get <Session>("Session");

            if (session == null)
            {
                await Task.WhenAll
                (
                    Global.WriteLogsAsync(RTU.Logger, "Http.InternalAPIs", $"No session is attached - Request: {requestMsg}", null, Global.ServiceName, LogLevel.Critical, correlationID),
                    RTU.WebSocket.CloseWebSocketAsync(websocket, WebSocketCloseStatus.PolicyViolation, "No session")
                ).ConfigureAwait(false);

                return;
            }

            // prepare
            var requestObj  = requestMsg.ToExpandoObject();
            var serviceName = requestObj.Get("ServiceName", "");
            var objectName  = requestObj.Get("ObjectName", "");
            var verb        = requestObj.Get("Verb", "GET").ToUpper();
            var query       = new Dictionary <string, string>(requestObj.Get("Query", new Dictionary <string, string>()), StringComparer.OrdinalIgnoreCase);

            query.TryGetValue("object-identity", out var objectIdentity);

            // visit logs
            if (Global.IsVisitLogEnabled)
            {
                await Global.WriteLogsAsync(RTU.Logger, "Http.Visits",
                                            $"Request starting {verb} " + $"/{serviceName}{(string.IsNullOrWhiteSpace(objectName) ? "" : $"/{objectName}")}{(string.IsNullOrWhiteSpace(objectIdentity) ? "" : $"/{objectIdentity}")}".ToLower() + (query.TryGetValue("x-request", out var xrequest) ? $"?x-request={xrequest}" : "") + " HTTPWS/1.1" + " \r\n" +