Exemple #1
0
        void sinkLoginFetchSuccess(TheRequestData pdata)
        {
            var tRes = TheCommonUtils.CArray2UTF8String(pdata.ResponseBuffer);

            MyRequestData = pdata;
            if (!string.IsNullOrEmpty(mTokenLocator))
            {
                if (mTokenLocator.StartsWith("HEADER:"))
                {
                    var tHead = mTokenLocator.Substring("HEADER:".Length);
                    if (pdata.Header.TryGetValue(tHead, out string tHeader))
                    {
                        eventTokenReceived?.Invoke(tHeader, pdata);
                        return;
                    }
                }
                else
                {
                    var pos = tRes.IndexOf(mTokenLocator); // "name=\"_token\" value=\"");
                    if (pos > 0)
                    {
                        pos += mTokenLocator.Length; /// "name=\"_token\" value=\"".Length;
                        var pos2   = tRes.IndexOf("\"", pos);
                        var tToken = tRes.Substring(pos, pos2 - pos);
                        eventTokenReceived?.Invoke(tToken, pdata);
                        return;
                    }
                }
            }
            eventTokenReceived?.Invoke(null, pdata);
        }
        private void sinkProcessResponse(TheRequestData pRequest)
        {
            if (pRequest.StatusCode >= 400 && pRequest.ResponseBuffer == null && !string.IsNullOrEmpty(pRequest.ErrorDescription))
            {
                pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(pRequest.ErrorDescription);
            }
            if (pRequest.ResponseBuffer == null && string.IsNullOrEmpty(pRequest.ResponseBufferStr))
            {
                pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array("EMPTY");
            }
            if (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript"))  //OK
            {
                pRequest.ResponseBufferStr = TheCommonUtils.CArray2UTF8String(pRequest.ResponseBuffer);
            }
            string tReqUri = pRequest.RequestUri.Host;

            if (pRequest.RequestUri.Port != 80)
            {
                tReqUri += ":" + pRequest.RequestUri.Port;
            }
            if (!string.IsNullOrEmpty(pRequest.ResponseBufferStr) && (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript")) && pRequest.ResponseBufferStr.IndexOf(tReqUri, StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                if (pRequest.SessionState.ARApp != Guid.Empty)
                {
                    TheRelayAppInfo tMyApp = TheThingRegistry.GetThingObjectByMID(MyBaseEngine.GetEngineName(), pRequest.SessionState.ARApp) as TheRelayAppInfo; //MyRelayApps.MyMirrorCache.GetEntryByFunc(s => s.cdeMID.Equals(pRequest.SessionState.ARApp));
                    if (tMyApp != null)
                    {
                        Uri tCloudUri = new Uri(pRequest.RequestUriString);
                        //pRequest.ResponseBufferStr = pRequest.ResponseBufferStr.Replace(pRequest.RequestUri.Host + ":" + pRequest.RequestUri.Port, new Uri(tMyApp.CloudUrl).Host + ":" + new Uri(tMyApp.CloudUrl).Port);
                        pRequest.ResponseBufferStr = pRequest.ResponseBufferStr.Replace(pRequest.RequestUri.Scheme + "://" + tReqUri, tCloudUri.Scheme + "://" + tCloudUri.Host + ":" + tCloudUri.Port);
                        pRequest.ResponseBuffer    = TheCommonUtils.CUTF8String2Array(pRequest.ResponseBufferStr);
                    }
                }
            }
            TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Response Bytes:{1} For Page:{0} Sent", pRequest.cdeRealPage, pRequest.ResponseBuffer != null ? pRequest.ResponseBuffer.Length : 0), eMsgLevel.l3_ImportantMessage));
            if (pRequest.ResponseBuffer != null)
            {
                //TheCommonUtils.SleepOneEye(5000, 100);
                TSM message3 = new TSM(MyBaseEngine.GetEngineName(), "WEBRELAY_RESPONSE")
                {
                    PLB = pRequest.ResponseBuffer
                };
                pRequest.ResponseBuffer    = null;
                pRequest.ResponseBufferStr = null;
                pRequest.RequestUriString  = pRequest.RequestUri.ToString();
                TSM tMSG = pRequest.CookieObject as TSM;
                pRequest.CookieObject = null;
                pRequest.PostData     = null;
                message3.PLS          = TheCommonUtils.SerializeObjectToJSONString(pRequest);
                TheCommCore.PublishToOriginator(tMSG, message3);
            }
        }
Exemple #3
0
 void sinkUploadDataCompleted(TheRequestData eResult)
 {
     if (eResult != null && eResult.ResponseBuffer != null && eResult.ResponseBuffer.Length > 0)
     {
         try
         {
             TheCDEKPIs.IncrementKPI(eKPINames.QSReceivedTSM);
             TheCDEKPIs.IncrementKPI(eKPINames.QKBReceived, eResult.ResponseBuffer.Length);
             if (eResult.StatusCode != 200)
             {
                 TheBaseAssets.MySYSLOG.WriteToLog(243, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("QueuedSender", $"Server responded with not-ok ...Code: {eResult.StatusCode} error: {TheCommonUtils.CArray2UTF8String(eResult.ResponseBuffer)}", eMsgLevel.l2_Warning), true);
                 FireSenderProblem(new TheRequestData()
                 {
                     ErrorDescription = $"{eResult.StatusCode}:Server responded with not-ok ...Code: {eResult.StatusCode}"
                 });
                 return;
             }
             List <TheDeviceMessage> tDevList = null;
             if (eResult.ResponseMimeType.Contains("zip"))
             {
                 tDevList = TheDeviceMessage.DeserializeJSONToObject(TheCommonUtils.cdeDecompressToString(eResult.ResponseBuffer));
             }
             else
             {
                 tDevList = TheDeviceMessage.DeserializeJSONToObject(TheCommonUtils.CArray2UTF8String(eResult.ResponseBuffer));
             }
             if (tDevList != null && tDevList.Count > 0)
             {
                 eResult.StatusCode = 0;
                 TheCorePubSub.ProcessClientDeviceMessage(this, eResult, tDevList);
             }
         }
         catch (Exception ee)
         {
             TheBaseAssets.MySYSLOG.WriteToLog(243, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("QueuedSender", $"Error in {MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l1_Error, ee.ToString()));
         }
     }
     else
     {
         if (MyTargetNodeChannel.SenderType != cdeSenderType.CDE_SERVICE)
         {
             TheBaseAssets.MySYSLOG.WriteToLog(243, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("QueuedSender", $"Did not receive any data from {MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l6_Debug));
         }
     }
 }
Exemple #4
0
        internal void sinkProcessLocation(TheRequestData pLocationState)
        {
            if (pLocationState.ResponseBuffer == null)
            {
                return;
            }
            TheVisitorLogData tlog = pLocationState.CookieObject as TheVisitorLogData;

            if (tlog != null)
            {
                MyLocation = tlog;
            }
            if (MyLocation == null)
            {
                MyLocation = new TheVisitorLogData();
            }

            string pLocation = TheCommonUtils.CArray2UTF8String(pLocationState.ResponseBuffer);

            if (!string.IsNullOrEmpty(pLocation))
            {
                try
                {
                    TheVisitorLogData tIP = TheCommonUtils.DeserializeJSONStringToObject <TheVisitorLogData>(pLocation);
                    if (tIP != null)
                    {
                        MyLocation.ip          = tIP.ip;
                        MyLocation.latitude    = tIP.latitude;
                        MyLocation.longitude   = tIP.longitude;
                        MyLocation.region_code = tIP.region_code;
                        MyLocation.region_name = tIP.region_name;
                        MyLocation.zip         = tIP.zip;
                        MyBaseThing?.FireEvent("NewVisitorLogged", MyBaseThing, null, true);
                        //TheREST.GetRESTAsync(new Uri(string.Format("http://a4544535456.api.wxbug.net/getLiveWeatherRSS.aspx?ACode=a4544535456&lat={0}&long={1}&UnitType=1&OutputType=1", MyLocation.Latitude, MyLocation.Longitude)), 0, MyWeather.sinkProcessWeather, null);
                    }
                }
                catch (Exception ee)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(512, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("VisitorLog", "Error processing Location ", eMsgLevel.l1_Error, ee.ToString() + ":::" + pLocation));
                }
            }
            MyVisitorLogStore?.UpdateItem(MyLocation);
        }
Exemple #5
0
        void ParseDevices(TheRequestData pdata)
        {
            MyRequestData = pdata;
            var tRes = TheCommonUtils.CArray2UTF8String(pdata.ResponseBuffer);

            eventDeviceDataReceived?.Invoke(tRes, pdata);

            if (IsConnected)
            {
                do
                {
                    TheCommonUtils.SleepOneEye(mReadyEvery, 100); //TheCommonUtils.CUInt(TheThing.GetSafePropertyNumber(MyBaseThing, "ReadEvery"))
                    if (WasDisconnected || !TheBaseAssets.MasterSwitch)
                    {
                        WasDisconnected = false;
                        return;
                    }
                } while (WaitForService);
                GetDevices();
            }
        }
 private static void sinkExternalIP(TheRequestData pResult)
 {
     if (pResult.CookieObject is ExIP texip)
     {
         Action <IPAddress, object> MyCall = texip.Callback;
         IPAddress externalIp = null;
         try
         {
             string getIpRegex = @"(?<=<body>.*)\d*\.\d*\.\d*\.\d*(?=</body>)";
             System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(getIpRegex);
             System.Text.RegularExpressions.Match m = r.Match(TheCommonUtils.CArray2UTF8String(pResult.ResponseBuffer));
             if (m.Success)
             {
                 externalIp = IPAddress.Parse(m.Value);
             }
         }
         catch (Exception e)
         {
             TheBaseAssets.MySYSLOG.WriteToLog(258, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheNetworkInfo", "GetExternalIp Exception", eMsgLevel.l1_Error, e.Message));
         }
         MyCall(externalIp, texip.Cookie);
     }
 }
        private void InterceptHttpRequest(TheRequestData pRequest, Guid MyApp, IBaseEngine MyBaseEngine, int pRequestTimeout) // TheRelayAppInfo MyApp)
        {
            if (MyApp == Guid.Empty)
            {
                return;
            }
            TheRequestData tOutBuffer = null;
            //NEW BY CM
            string tMagixc = Guid.NewGuid().ToString();

            ReqBuffer.AddOrUpdateItem(TheCommonUtils.CGuid(tMagixc), null, null);
            if (!MyBaseEngine.GetEngineState().IsService) // || string.IsNullOrEmpty(MyApp.TargetUrl) || !TheCommonUtils.IsLocalhost(MyApp.HostUrl)) //  !MyApp.HostUrl.Equals(TheBaseAssets.MyServiceHostInfo.MyStation URL))
            {
                TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "WEBRELAY_REQUEST")
                {
                    PLB = pRequest.PostData
                };
                pRequest.PostData       = null;
                pRequest.ResponseBuffer = null;
                if (!string.IsNullOrEmpty(pRequest.CookieString))
                {
                    pRequest.CookieString += ";";
                }
                else
                {
                    pRequest.CookieString = "";
                }
                pRequest.CookieString += tMagixc;
                //if (string.IsNullOrEmpty(MyApp.CloudUrl)) MyApp.CloudUrl = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false);
                if (string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.RootDir))
                {
                    pRequest.RequestUriString = pRequest.RequestUri.ToString();
                }
                else
                {
                    pRequest.RequestUriString = pRequest.RequestUri.Scheme + "://" + pRequest.RequestUri.Host + ":" + pRequest.RequestUri.Port + pRequest.cdeRealPage;
                    if (!string.IsNullOrEmpty(pRequest.RequestUri.Query))
                    {
                        pRequest.RequestUriString += "?" + pRequest.RequestUri.Query;
                    }
                }
                TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0}", pRequest.RequestUriString), eMsgLevel.l6_Debug));

                tTSM.PLS = TheCommonUtils.SerializeObjectToJSONString(pRequest);
                tTSM.SID = pRequest.SessionState.GetSID(); //.SScopeID;
                TheCommCore.PublishCentral(tTSM);          //  .PublishToNode(MyApp.HostUrl, pRequest.SessionState.SScopeID, tTSM);
            }
            else
            {
                TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("AppID:{1} Requesting Page:{0}", pRequest.cdeRealPage, MyApp)));
                ReadHttpPage(pRequest, MyApp, tMagixc, sinkResults);
            }
            int SyncFailCount      = 0;
            ManualResetEvent MyMRE = new ManualResetEvent(false);

            do
            {
                try
                {
                    tOutBuffer = ReqBuffer.GetEntryByID(TheCommonUtils.CGuid(tMagixc));
                    if (tOutBuffer != null)
                    {
                        pRequest.ResponseBuffer   = tOutBuffer.ResponseBuffer;
                        pRequest.ResponseMimeType = tOutBuffer.ResponseMimeType;
                        if (pRequest.SessionState.StateCookies == null)
                        {
                            pRequest.SessionState.StateCookies = new cdeConcurrentDictionary <string, string>();
                        }
                        if (tOutBuffer.SessionState != null && tOutBuffer.SessionState.StateCookies != null && tOutBuffer != pRequest)
                        {
                            foreach (KeyValuePair <String, String> kvp in tOutBuffer.SessionState.StateCookies.GetDynamicEnumerable())
                            {
                                string value;
                                if (!pRequest.SessionState.StateCookies.TryGetValue(kvp.Key, out value))
                                {
                                    pRequest.SessionState.StateCookies.TryAdd(kvp.Key, kvp.Value);
                                }
                                else
                                {
                                    pRequest.SessionState.StateCookies[kvp.Key] = kvp.Value;
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(tOutBuffer.ResponseBufferStr))
                        {
                            pRequest.ResponseBufferStr = tOutBuffer.ResponseBufferStr;
                        }
                        else
                        {
                            if (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript"))  //OK
                            {
                                pRequest.ResponseBufferStr = TheCommonUtils.CArray2UTF8String(tOutBuffer.ResponseBuffer);
                            }
                        }
                        string tReqUri = pRequest.RequestUri.Host;
                        if (pRequest.RequestUri.Port != 80)
                        {
                            tReqUri += ":" + pRequest.RequestUri.Port;
                        }
                        TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Got Response Page:{0}", tReqUri), eMsgLevel.l6_Debug));

                        if (!string.IsNullOrEmpty(pRequest.ResponseBufferStr) && (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript")) && pRequest.ResponseBufferStr.IndexOf(tReqUri, StringComparison.CurrentCultureIgnoreCase) >= 0)
                        {
                            if (pRequest.SessionState.ARApp != null && pRequest.SessionState.ARApp != Guid.Empty)
                            {
                                TheRelayAppInfo tMyApp = TheThingRegistry.GetThingObjectByMID(MyBaseEngine.GetEngineName(), pRequest.SessionState.ARApp) as TheRelayAppInfo;
                                //MyRelayApps.MyMirrorCache.GetEntryByFunc(s => s.cdeMID.Equals(pRequest.SessionState.ARApp));

                                if (tMyApp != null && tMyApp.CloudUrl != null)
                                {
                                    Uri tCloudUri = TheCommonUtils.CUri(tMyApp.CloudUrl, false);
                                    if (!string.IsNullOrEmpty(pRequest.NewLocation))
                                    {
                                        pRequest.NewLocation = pRequest.NewLocation.Replace(pRequest.RequestUri.Scheme + "://" + tReqUri, tCloudUri.Scheme + "://" + tCloudUri.Host + ":" + tCloudUri.Port);
                                    }
                                    TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Patching Uri from:{0} to:{1}", tReqUri, tCloudUri), eMsgLevel.l6_Debug));

                                    pRequest.ResponseBufferStr = pRequest.ResponseBufferStr.Replace(pRequest.RequestUri.Scheme + "://" + tReqUri, tCloudUri.Scheme + "://" + tCloudUri.Host + ":" + tCloudUri.Port);
                                    pRequest.ResponseBuffer    = TheCommonUtils.CUTF8String2Array(pRequest.ResponseBufferStr);
                                }
                            }
                        }
                        break;
                    }
                    MyMRE.WaitOne(50);
                    SyncFailCount++; if (SyncFailCount > (pRequestTimeout * 20))
                    {
                        if (TheCommonUtils.IsMono())
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(400, new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0} FAILED", pRequest.cdeRealPage), eMsgLevel.l1_Error));
                        }
                        else
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0} FAILED", pRequest.cdeRealPage), eMsgLevel.l1_Error));
                        }
                        break;
                    }
                }
                catch (Exception ee)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Error during HttpIntercept for Page:{0}", pRequest.cdeRealPage), eMsgLevel.l1_Error, ee.ToString()));
                }
            } while (tOutBuffer == null);
            if (MyMRE != null)
            {
                MyMRE = null; //.Dispose();
            }
            if ((pRequest.ResponseBuffer == null && string.IsNullOrEmpty(pRequest.ResponseBufferStr)) || pRequest.StatusCode != 0)
            {
                if (pRequest.StatusCode == 0)
                {
                    pRequest.StatusCode = 404;
                }
            }
            else
            {
                pRequest.AllowStatePush = true;
                pRequest.StatusCode     = 200;
            }
            ReqBuffer.RemoveAnItemByID(TheCommonUtils.CGuid(tMagixc), null);
        }
Exemple #8
0
        void sinkRegResult(TheRequestData pData)
        {
            if (pData.CookieObject is Action <string, TheUPnPDeviceInfo> tResultCallback)
            {
                switch (pData.StatusCode)
                {
                case (int)eHttpStatusCode.OK:
                    TheUPnPDeviceInfo tInfo = null;
                    try
                    {
                        if (pData.PostData != null && pData.PostData.Length > 0)
                        {
                            tInfo = TheCommonUtils.DeserializeJSONStringToObject <TheUPnPDeviceInfo>(TheCommonUtils.CArray2UTF8String(pData.ResponseBuffer));
                        }
                        tResultCallback("OK", tInfo);
                    }
                    catch
                    {
                        tResultCallback("FAILED-No valid TheUPnPDeviceInfo received", null);
                    }
                    break;

                case (int)eHttpStatusCode.ServerError:
                    tResultCallback("FAILED-Server Not found or has errors", null);
                    break;

                case (int)eHttpStatusCode.NotAcceptable:
                    tResultCallback("FAILED-Server failed to register device", null);
                    break;

                default:
                    tResultCallback("FAILED-Unkown error", null);
                    break;
                }
            }
        }
Exemple #9
0
        internal void ProcessIncomingData(string pPostString, byte[] pPostData, int pPostDataLength)
        {
            if (!IsActive)
            {
                return;
            }

            if (MySessionRequestData == null || MySessionRequestData?.SessionState?.HasExpired == true)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4360, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSProcessor", $"Incoming Data on expired session ({MySessionRequestData?.SessionState?.HasExpired}) detected - shutting down websockets", eMsgLevel.l6_Debug));
                Shutdown(false, "1600:Incoming Data on expired session detected - shutting down websockets");
                return;
            }
            TheRequestData tRequestData = TheRequestData.CloneForWS(MySessionRequestData);

            TheCDEKPIs.IncrementKPI(eKPINames.QSReceivedTSM);
            tRequestData.PostData    = pPostData;
            tRequestData.PostDataIdx = 0;
            if (pPostData == null)
            {
                tRequestData.PostDataLength = 0;
            }
            else
            {
                tRequestData.PostDataLength = pPostDataLength > 0 ? pPostDataLength : pPostData.Length;
                TheCDEKPIs.IncrementKPI(eKPINames.QKBReceived, tRequestData.PostDataLength);
            }

            if (IsClient)
            {
                string cmdString = "";
                try
                {
                    List <TheDeviceMessage> tDevList;
                    if (tRequestData.PostData == null && !string.IsNullOrEmpty(pPostString))
                    {
                        if (pPostString[0] != '[')
                        {
                            return;
                        }
                        tDevList = TheDeviceMessage.DeserializeJSONToObject(pPostString);
                    }
                    else
                    {
                        if (tRequestData.PostData == null)
                        {
                            return;                              //Edge Case but could happen - all what follows required ProcessClientDeviceMsg
                        }
                        cmdString = tRequestData.PostData[0] == (byte)'[' ? TheCommonUtils.CArray2UTF8String(tRequestData.PostData, 0, tRequestData.PostDataLength) : TheCommonUtils.cdeDecompressToString(tRequestData.PostData, 0, tRequestData.PostDataLength);
                        tDevList  = TheDeviceMessage.DeserializeJSONToObject(cmdString);
                    }

                    TheCorePubSub.ProcessClientDeviceMessage(MyQSender, tRequestData, tDevList);
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(4361, new TSM("WSClient", "Message-Received Processing Error", eMsgLevel.l1_Error, e.ToString()));
                }
            }
            else
            {
                try
                {
                    if (tRequestData.PostData == null && !string.IsNullOrEmpty(pPostString))
                    {
                        tRequestData.PostData       = TheCommonUtils.CUTF8String2Array(pPostString);
                        tRequestData.PostDataLength = tRequestData.PostData.Length;
                    }
                    if (TheCommCore.MyHttpService != null)
                    {
                        TheCommCore.MyHttpService.cdeProcessPost(tRequestData);
                    }
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(4362, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "WebSocketServer-ProcessRequest Error", eMsgLevel.l1_Error, e.ToString()));
                }
            }
            if (MySessionRequestData.SessionState == null)
            {
                MySessionRequestData.SessionState = tRequestData.SessionState;
            }
            if (MySessionRequestData.DeviceID == Guid.Empty)
            {
                MySessionRequestData.DeviceID = tRequestData.DeviceID;
            }
            if (tRequestData.SessionState != null && MyQSender != null)
            {
                if (MyQSender.IsConnecting)
                {
                    MyQSender.IsConnected = true;
                    if (MyQSender.eventConnected != null)
                    {
                        TheCommonUtils.cdeRunAsync("QueueConnected", true, (p) =>
                        {
                            MyQSender?.eventConnected?.Invoke(MyQSender, MyQSender.MyTargetNodeChannel);
                        });
                    }
                    MyQSender.MyISBlock?.FireEvent("Connected");
                }
                //NEW3.124: Reset Heartbeat on Ws Post
                MyQSender.ResetHeartbeatTimer(false, tRequestData.SessionState);
            }
            else
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4361, TSM.L(eDEBUG_LEVELS.ESSENTIALS)?null: new TSM("WSClient", $"No Request Session {tRequestData.SessionState!=null} or no QSender Found {MyQSender!=null}) IsClient={IsClient}", eMsgLevel.l2_Warning));
            }


            try
            {
                if (tRequestData.ResponseBuffer != null)
                {
                    PostToSocket(null, tRequestData.ResponseBuffer, IsClient, false);
                }
            }
            catch (Exception ex) // For debugging
            {
                //if (eventClosed != null)
                //  eventClosed("Connection Error: " + ex.ToString());
                Shutdown(true, "1601:PostToSocket Error: " + ex);
            }
        }
        internal static void ExecuteCommand(string pInTopic, TheQueuedSender pQSender, bool DoSendBackBuffer, TheRequestData pRequestData, List <TheDeviceMessage> pDevMessageList)
        {
            if (pRequestData == null)
            {
                return;
            }

            #region Precheck on Execute Conditions
            if (pQSender?.MyTargetNodeChannel == null)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("CoreComm", "Enter Execute Command: OrgChannel is Null - not allowed ", eMsgLevel.l2_Warning));
                pRequestData.ResponseBufferStr = "ERR: Illegal Request";
                pRequestData.StatusCode        = 400;// (int)nsCDEngine.Communication.HttpService.eHttpStatusCode.NotAcceptable;
                return;
            }
            if (!TheBaseAssets.MasterSwitch)
            {
                pRequestData.ResponseBufferStr = "ERR: Service is shutting Down..."; return;
            }
            if (pRequestData.SessionState == null && TheBaseAssets.MySession != null)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("CoreComm", "Enter Execute Command: Session no longer alive - Topic:" + pInTopic, eMsgLevel.l2_Warning));
                pRequestData.ResponseBufferStr = "ERR: Session no longer alive";
                pRequestData.StatusCode        = 401; //(int)nsCDEngine.Communication.HttpService.eHttpStatusCode.NotAcceptable;
                return;
            }
            #endregion

            try
            {
                if (pDevMessageList == null)
                {
                    #region Received BINARY Data in Post Data - Parsing
                    //REVIEW: This should no longer be used in the future...all telegrams should come in as HTTP Bodies
                    if (pRequestData.PostData != null && pRequestData.PostData.Length > 0 && pRequestData.PostDataIdx >= 0)
                    {
                        int tPostDataLength = pRequestData.PostData.Length;
                        if (pRequestData.PostDataLength > 0)
                        {
                            tPostDataLength = pRequestData.PostDataLength;
                        }
                        if ((tPostDataLength - pRequestData.PostDataIdx) == 1)
                        {
                            if (pQSender.MyTargetNodeChannel.SenderType == cdeSenderType.NOTSET)
                            {
                                pQSender.MyTargetNodeChannel.SenderType = (cdeSenderType)(pRequestData.PostData[0] - 0x30);
                                TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("CoreComm", $"ChannelChange: Was NOTSET and now is now: {pQSender.MyTargetNodeChannel.SenderType}", eMsgLevel.l3_ImportantMessage));
                            }
                        }
                        else
                        {
                            try
                            {
                                string tStr  = null;
                                bool   isBin = false;
                                if (pRequestData.ResponseMimeType.ToLower().Contains("zip"))
                                {
                                    tStr  = TheCommonUtils.cdeDecompressToString(pRequestData.PostData, pRequestData.PostDataIdx, tPostDataLength - pRequestData.PostDataIdx);
                                    isBin = true;
                                }
                                else
                                {
                                    tStr = TheCommonUtils.CArray2UTF8String(pRequestData.PostData, pRequestData.PostDataIdx, tPostDataLength - pRequestData.PostDataIdx);
                                }

                                pDevMessageList = TheDeviceMessage.DeserializeJSONToObject(tStr);

                                if (pQSender.MyTargetNodeChannel.SenderType == cdeSenderType.NOTSET)
                                {
                                    pQSender.MyTargetNodeChannel.SenderType = isBin ? cdeSenderType.CDE_SERVICE : cdeSenderType.CDE_JAVAJASON;
                                    TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("CoreComm", $"ChannelChange: Was NOTSET and now is now: {pQSender.MyTargetNodeChannel.SenderType}", eMsgLevel.l3_ImportantMessage));
                                }
                            }
                            catch (Exception eee)
                            {
                                string remot = "unkown";
                                if (pRequestData.SessionState != null && pRequestData.SessionState.MyDevice != Guid.Empty)
                                {
                                    remot = pRequestData.SessionState.MyDevice.ToString();
                                }
                                TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("CoreComm", "Execute Command received JSON package failed", eMsgLevel.l2_Warning, $"{pRequestData.RequestUri} {remot} {eee}"));
                            }
                        }
                    }
                    #endregion
                }
                DoExecuteCommand(pInTopic, pQSender, DoSendBackBuffer, pRequestData, pDevMessageList);
            }
            catch (Exception eeee)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("CoreComm", "Execute Command failed", eMsgLevel.l2_Warning, $"{pRequestData.RequestUri} {eeee}"));
            }
        }
Exemple #11
0
        internal override void PostToSocket(TheDeviceMessage pMsg, byte[] pPostBuffer, bool PostAsBinary, bool IsInitialConnect)
        {
            TheDiagnostics.SetThreadName("WSPostToSocketCSWS:" + (MyQSender.MyTargetNodeChannel?.ToString() ?? "DEAD"));

            if (MyQSender != null && !MyQSender.IsConnected && !IsInitialConnect)
            {
                Shutdown(true, "1653:QSenderCSWS not connected but Posting in illegal state");
                return;
            }

            if (!ProcessingAllowed)         //NEW:V3BETA2: New Waiting Algorythm
                WaitUntilProcessingAllowed();

            if (!IsActive || !TheBaseAssets.MasterSwitch)
                return;

            if (websocket == null && webSocketSession==null)
            {
                eventClosed?.Invoke("1654:WebSockets are down");
                return;
            }
            ProcessingAllowed = false;

            try
            {
                if (pPostBuffer != null)
                {
                    TheCDEKPIs.IncrementKPI(eKPINames.QKBSent, pPostBuffer.Length);
                    if (PostAsBinary)
                    {
                        if (webSocketSession != null)
                            webSocketSession.SendB(pPostBuffer);
                        else
                        {
                            websocket?.Send(pPostBuffer);
                        }
                    }
                    else
                    {
                        if (webSocketSession != null)
                            webSocketSession.SendB(TheCommonUtils.CArray2UTF8String(pPostBuffer));
                        else
                        {
                            websocket?.Send(TheCommonUtils.CArray2UTF8String(pPostBuffer));
                        }
                    }
                }
                else
                {
                    string toSend = TheCommonUtils.SerializeObjectToJSONString(pMsg);
                    if (PostAsBinary)
                    {
                        byte[] toSendb = TheCommonUtils.CUTF8String2Array(toSend);
                        TheCDEKPIs.IncrementKPI(eKPINames.QKBSent, toSendb.Length);
                        if (webSocketSession != null)
                            webSocketSession.SendB(toSendb);
                        else
                        {
                            websocket?.Send(toSendb);
                        }
                    }
                    else
                    {
                        if (webSocketSession != null)
                            webSocketSession.SendB(toSend);
                        else
                        {
                            websocket?.Send(toSend);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Shutdown(true, "1655:DoPostToSocketCSWS had a fault: "+e);
            }

            if (mre != null)
                ProcessingAllowed = true;
        }