public async Task SubscriberHandlesExceptionsOnHandle()
        {
            // Setup

            var count     = 0;
            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var socket    = new WebSocketSubscriber(messenger.Object, log);

            socket.Subscribe(s =>
            {
                if (count++ == 0)
                {
                    throw new InvalidOperationException();
                }
                return(Task.FromResult(0));
            });

            // Execute

            socket.Start();
            await Task.Delay(100);

            socket.Stop();
            socket.Dispose();

            // Check

            messenger.Verify(m => m.GetResponseAsync(It.IsAny <CancellationToken>()), Times.AtLeast(2));

            Assert.True(count > 1); // Expecting messages to continue
            // Expecting logged exception
            Assert.True(log.ContainsErrors());
        }
        public async Task MethodsStartStopAreIdempotent()
        {
            // Setup

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();

            var income = new List <string>();
            var socket = new WebSocketSubscriber(messenger.Object, log);

            socket.Subscribe(s => { income.Add(s); return(Task.FromResult(0)); });

            // Execute

            socket.Start();
            socket.Start();
            socket.Start();
            await Task.Delay(50);

            socket.Stop();
            socket.Stop();
            socket.Stop();
            socket.Dispose();
            socket.Dispose();
            socket.Dispose();

            // Check

            // Should receive all 'i': from 1 to 10
            Assert.True(income.Count > 0);

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
        public async Task SubscriberHandlesExceptionsOnResponse()
        {
            // Setup
            //
            var count     = 0;
            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();

            messenger
            .Setup(m => m.GetResponseAsync(It.IsAny <CancellationToken>()))
            .Callback(() =>
            {
                if (count++ == 0)
                {
                    throw new TimeoutException();
                }
            }).Returns(Task.FromResult(""));
            var socket = new WebSocketSubscriber(messenger.Object, log);

            // Execute

            socket.Start();
            await Task.Delay(ReconnectionTime.Add(TimeSpan.FromMilliseconds(500))); // wait for connection retry

            socket.Stop();
            socket.Dispose();

            // Check

            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(2));
            messenger.Verify(m => m.GetResponseAsync(It.IsAny <CancellationToken>()), Times.AtLeast(2));

            // Expecting logged exception
            Assert.True(log.ContainsErrors());
        }
        public async Task SubscriberCanBeRestartedMultipleTimes()
        {
            // Setup

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();

            var income = new List <string>();
            var socket = new WebSocketSubscriber(messenger.Object, log);

            socket.Subscribe(s => { income.Add(s); return(Task.FromResult(0)); });

            // Execute

            for (var i = 0; i < 10; i++)
            {
                messenger
                .Setup(m => m.GetResponseAsync(It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult(i.ToString()));

                socket.Start();
                await Task.Delay(50);

                socket.Stop();
            }
            socket.Dispose();

            // Check

            // Should receive all 'i': from 1 to 10
            Assert.Equal(45, income.GroupBy(i => i).Select(g => Int32.Parse(g.Key)).Sum());

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
        public async Task HeartbeatDoesNotRestartAfterStop()
        {
            // Setup

            var heartbeat = TimeSpan.FromMilliseconds(500);
            var waitTime  = TimeSpan.FromMilliseconds(1000);

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var socket    = new WebSocketSubscriber(messenger.Object, log, heartbeat);

            // Execute

            socket.Start();
            await Task.Delay(TimeSpan.FromMilliseconds(50)); // give time to charge heartbeat

            socket.Stop();
            await Task.Delay(waitTime); // wait for possible heartbeat recharge

            socket.Dispose();

            // Check

            // 1 call Connect/Stop
            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));
            messenger.Verify(m => m.StopAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
        public async Task StopCallInterruptsGetResponse()
        {
            // Setup

            var waitTime      = TimeSpan.FromMilliseconds(100);
            var controlTime   = TimeSpan.FromMilliseconds(300);
            var executionTime = TimeSpan.FromSeconds(10);
            var log           = new LogToMemory();

            var messenger = CreateDefaultMockMessenger();

            messenger
            .Setup(m => m.GetResponseAsync(It.IsAny <CancellationToken>()))
            .Returns <CancellationToken>(async token =>
            {
                await Task.Delay(executionTime, token);     // Emulate long connection
                return("");
            });
            var socket = new WebSocketSubscriber(messenger.Object, log);

            // Execute

            var watch = new Stopwatch();

            watch.Start();

            socket.Start();
            await Task.Delay(waitTime); // wait connection

            socket.Stop();
            socket.Dispose();

            watch.Stop();

            // Check

            // Connection must be interrupted
            Assert.True(watch.Elapsed < controlTime);

            // 1 call Connect/Stop
            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));
            messenger.Verify(m => m.StopAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
        public async Task SimpleCycleExecutesCorrectly()
        {
            // Setup

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var socket    = new WebSocketSubscriber(messenger.Object, log);

            // Execute

            socket.Start();
            await Task.Delay(TimeSpan.FromMilliseconds(100)); // wait cycle to perform

            socket.Stop();
            socket.Dispose();

            // Check

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
        public async Task SubscriberRestartsWhenNoMessagesReceived()
        {
            // Setup

            var heartbeat     = TimeSpan.FromSeconds(1);
            var waitTime      = TimeSpan.FromSeconds(1.5);
            var executionTime = TimeSpan.FromSeconds(2);

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();

            messenger
            .Setup(m => m.GetResponseAsync(It.IsAny <CancellationToken>()))
            .Returns <CancellationToken>(async token =>
            {
                await Task.Delay(executionTime, token); return("");    // Emulate no messages for a long time
            });

            var socket = new WebSocketSubscriber(messenger.Object, log, heartbeat);

            // Execute

            socket.Start();
            await Task.Delay(waitTime); // wait cycle and restart to perform

            socket.Stop();
            socket.Dispose();

            // Check

            // Heartbeat restart causes 2 times connect/stop
            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(2));
            messenger.Verify(m => m.StopAsync(It.IsAny <CancellationToken>()), Times.Exactly(2));

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
예제 #9
0
    public override V3Message execute( Request message, RequestContext context )
    {
      object returnValue = null;

      switch ( operation )
      {
        case SUBSCRIBE_OPERATION:
          {
            IDestination destObj =
              ORBConfig.GetInstance().GetDataServices().GetDestinationManager().GetDestination(destination);
            Hashtable headers = new Hashtable();

            RTMPConnection connection = (RTMPConnection) ConnectionHub.getConnectionLocal();

            if (destObj != null)
            {
              String selectorName = (String) this.headers["DSSelector"];
              String subtopic = (String) this.headers["DSSubtopic"];
              String dsId = connection == null ? (String) this.headers["DSId"] : connection.GetHashCode().ToString();
              String channel = (String) this.headers["DSEndpoint"];

              Subscriber subscriber = SubscriptionsManager.GetInstance().getSubscriber(
                Subscriber.buildId(dsId, destObj.GetName(), subtopic, selectorName));

              if (clientId == null || clientId.Equals(""))
                clientId = Guid.NewGuid().ToString().ToUpper();

              if (subscriber != null)
              {
                if (subscriber.addClient(clientId.ToString()))
                  destObj.GetServiceHandler().HandleSubscribe(subscriber, clientId.ToString(), this);

                return new AckMessage(messageId, clientId, null, headers);
              }

              object wsContext = ThreadContext.getProperties()[ORBConstants.WEB_SOCKET_MODE];

              if (wsContext != null)
              {
                subscriber = new WebSocketSubscriber(selectorName, destObj, (UserContext) wsContext);
              }
              else if (connection != null)
              {
                subscriber = new DedicatedSubscriber(selectorName, destObj);
                subscriber.setChannelId(RTMPHandler.getChannelId());
                subscriber.setConnection(connection);
              }
              else
              {
                subscriber = SubscriberFactory.CreateSubscriber(channel, selectorName, destObj);
              }

              subscriber.setDSId(dsId);
              subscriber.setSubtopic(subtopic);
              subscriber.addClient((String) clientId);

              try
              {
                SubscriptionsManager.GetInstance().AddSubscriber(dsId, destObj.GetName(), subscriber);
              }
              catch (Exception e)
              {
                if (Log.isLogging(LoggingConstants.EXCEPTION))
                  Log.log(LoggingConstants.EXCEPTION, e);
              }

              destObj.GetServiceHandler().HandleSubscribe(subscriber, clientId.ToString(), this);
            }
            else
            {
              String error = "Unknown destination " + destination + ". Cannot handle subscription request";

              if (Log.isLogging(LoggingConstants.ERROR))
                Log.log(LoggingConstants.ERROR, error);

              return new ErrMessage(messageId, new Exception(error));
            }

            return new AckMessage(messageId, clientId, null, headers);
          }
          break;
        case UNSUBSCRIBE_OPERATION:
          {
            String subtopic = (String) this.headers["DSSubtopic"];
            String dsId = (String) this.headers["DSId"];
            String selectorName = (String) this.headers["DSSelector"];

            RTMPConnection connection = (RTMPConnection) ConnectionHub.getConnectionLocal();

            if (connection != null)
              dsId = connection.GetHashCode().ToString();

            Subscriber subscriber = SubscriptionsManager.GetInstance().getSubscriber(
              Subscriber.buildId(dsId, destination, subtopic, selectorName));

            if (subscriber != null)
            {
              SubscriptionsManager.GetInstance().unsubscribe(subscriber, clientId.ToString(), this);
            }
          }
          break;
        case DISCONNECT_OPERATION:
          {
            String dsId = (String) this.headers["DSId"];
            RTMPConnection connection = (RTMPConnection) ConnectionHub.getConnectionLocal();

            if (connection != null)
              dsId = connection.GetHashCode().ToString();

            SubscriptionsManager subscriptionsManager = SubscriptionsManager.GetInstance();
            List<Subscriber> subscribers = subscriptionsManager.getSubscribersByDsId(dsId);

            if (subscribers != null)
              foreach (Subscriber subscriber in subscribers )
                if (subscriber != null)
                  subscriptionsManager.unsubscribe(subscriber, this);

            subscriptionsManager.removeSubscriber(dsId);
          }
          break;
        case POLL_OPERATION:
          {
            String dsId = (String) this.headers["DSId"];

            RTMPConnection connection = (RTMPConnection) ConnectionHub.getConnectionLocal();

            if (connection != null)
              dsId = connection.GetHashCode().ToString() + "";

            try
            {
              WebORBArray<V3Message> messages =
                new WebORBArray<V3Message>(SubscriptionsManager.GetInstance().getMessages(dsId));

              if (messages.Count == 0)
                return new AckMessage(null, null, null, new Hashtable());

              return new CommandMessage(CLIENT_SYNC_OPERATION, messages);
            }
            catch (Exception e)
            {
              String error = "Invalid client id " + dsId;

              if (Log.isLogging(LoggingConstants.ERROR))
                Log.log(LoggingConstants.ERROR, error, e);

              return new ErrMessage(messageId, new Exception(error));
            }
          }
          break;
        case CLIENT_PING_OPERATION:
          {
            Hashtable headers = new Hashtable();

            RTMPConnection connection = (RTMPConnection) ConnectionHub.getConnectionLocal();
            if (connection != null)
              headers.Add("DSId", connection.GetHashCode().ToString());
            else
              headers.Add("DSId", Guid.NewGuid().ToString().ToUpper());

            return new AckMessage(messageId, clientId, null, headers);
          }
          break;
        case LOGOUT_OPERATION:
          {
            ThreadContext.setCallerCredentials(null, null);
            Thread.CurrentPrincipal = null;
          }
          break;
        case LOGIN_OPERATION:
          {

            String credentials = (String) ((IAdaptingType) ((object[]) body.body)[0]).defaultAdapt();
            byte[] bytes = Convert.FromBase64String(credentials);
            credentials = new String(Encoding.UTF8.GetChars(bytes));
            IAuthenticationHandler authHandler = ORBConfig.GetInstance().getSecurity().GetAuthenticationHandler();

            if (authHandler == null)
            {
              ErrMessage errorMessage = new ErrMessage(messageId, new ServiceException("Missing authentication handler"));
              errorMessage.faultCode = "Client.Authentication";
              return errorMessage;
            }

            int index = credentials.IndexOf(":");
            string userid = null;
            string password = null;

            if (index != -1 && index != 0 && index != credentials.Length - 1)
            {
              userid = credentials.Substring(0, index);
              password = credentials.Substring(index + 1);

              try
              {
                IPrincipal principal = authHandler.CheckCredentials(userid, password, message);

                try
                {
                  Thread.CurrentPrincipal = principal;
                  ThreadContext.currentHttpContext().User = principal;
                }
                catch (Exception exception)
                {
                  if (Log.isLogging(LoggingConstants.ERROR))
                    Log.log(LoggingConstants.ERROR,
                            "Unable to set current principal. Make sure your current permission set allows Principal Control",
                            exception);

                  throw exception;
                }

                Credentials creds = new Credentials();
                creds.userid = userid;
                creds.password = password;
                ThreadContext.setCallerCredentials(creds, principal);
              }
              catch (Exception exception)
              {
                ErrMessage errorMessage = new ErrMessage(messageId, exception);
                errorMessage.faultCode = "Client.Authentication";
                return errorMessage;
              }
            }
            else
            {
              ErrMessage errorMessage = new ErrMessage(messageId, new ServiceException("Invalid credentials"));
              errorMessage.faultCode = "Client.Authentication";
              return errorMessage;
            }
          }
          break;
      }

      return new AckMessage( messageId, clientId, returnValue, new Hashtable() );
    }
예제 #10
0
        public async Task PostAsync([FromBody] JObject MessageJobj)
        {
            bool   outgoing;
            string ChannelUUId = "";

            string SocketPublishUrl = _configuration.GetValue <string>("RequestUrls:WebSocketPublish");

            string MdeiaType = "0";

            LogProperties.info("Whats api called");


            try

            {
                outgoing = (bool)MessageJobj["outgoing"];
                //               "sender": "919966226645",
                //"recipient": "2df4b63c-135a-4206-91d3-8132dfe64f22",
                if (!outgoing)
                {
                    ChannelUUId = Convert.ToString(MessageJobj["recipient"]);
                }

                WidgetChannels widgetChannel = null;
                Widgets        widget        = null;
                try
                {
                    widgetChannel = _context.WidgetChannels.Where(wc => wc.ChanneUUID == ChannelUUId && wc.ConversationTypeId == 2).FirstOrDefault();
                    LogProperties.info("widgetChannel for message: " + widgetChannel.WidgetId);

                    widget = _context.Widgets.Where(w => w.Id == widgetChannel.WidgetId).FirstOrDefault();
                    LogProperties.info("widget for message: " + widgetChannel.WidgetId);
                }
                catch (Exception dbEx)
                {
                    widgetChannel = _context.WidgetChannels.Where(wc => wc.Id == 2).FirstOrDefault();
                    LogProperties.info("widgetChannel for message catch: " + widgetChannel.WidgetId);

                    widget = _context.Widgets.Where(w => w.Id == 6).FirstOrDefault();
                    LogProperties.info("widget for message catch: " + widget.Id);
                }
                // var widgetChannel = _context.WidgetChannels.Where(wc => wc.ChanneUUID == ChannelUUId && wc.ConversationTypeId == 2).FirstOrDefault();
                // LogProperties.info("widgetChannel for message: " + widgetChannel.WidgetId );



                //[HttpPost("{account_id}/widgets/{widget_id}/conversations/{conversation_id}/{is_endchat}/replies")]
                if (widget != null)
                {
                    if (!outgoing)
                    {
                        JObject jObject = new JObject();
                        jObject = JObject.Parse(MessageJobj.ToString());
                        //    await ProcessIncomingMessageAsync(widget, MessageJobj);

                        LogProperties.info("Whats api ougoing enter");
                        string CustomerMobile       = "";
                        string CustomerName         = "";
                        string CustomerProfileImage = "";

                        int     AccountId              = widget.AccountId;
                        int     WidgetId               = widget.Id;
                        int     ConverstationId        = 0;
                        long    ConverstationMessageId = 0;
                        int     CustomerId             = 0;
                        JObject CustJobj               = new JObject();

                        CustomerMobile       = Convert.ToString(MessageJobj["sender"]);
                        ChannelUUId          = Convert.ToString(MessageJobj["recipient"]);
                        CustomerName         = Convert.ToString(MessageJobj["payload"]["user"]["name"]);
                        CustomerProfileImage = Convert.ToString(MessageJobj["payload"]["user"]["image"]);

                        ConversationsController conController = new ConversationsController(_context, _configuration);



                        CustJobj   = GetCustomerId(AccountId, CustomerName, CustomerMobile, CustomerProfileImage);
                        CustomerId = Convert.ToBoolean(CustJobj["Success"]) ? Convert.ToInt32(CustJobj["CustomerId"]) : -1;
                        LogProperties.info("Whats api after get customer");
                        var PrevConverstations = (from Con in _context.Conversations
                                                  where Con.WidgetId == WidgetId && Con.CustomerId == CustomerId
                                                  orderby Con.Id descending
                                                  select new {
                            Con.Id,
                            Con.AgentId
                        }).FirstOrDefault();

                        if (PrevConverstations != null)
                        {
                            ConverstationId = PrevConverstations.Id;
                        }
                        LogProperties.info("Whats api after Conversations");
                        var PrevConMessages = (from ConMess in _context.ConversationMessages
                                               where ConMess.ConversationId == ConverstationId
                                               orderby ConMess.Id descending
                                               select new
                        {
                            ConMess.Id,
                            ConMess.CreatedTimeUTC,
                            ConMess.AgentId
                        }).FirstOrDefault();

                        DateTime RecentMsgTime;
                        if (PrevConMessages != null && PrevConMessages.Id > 0)
                        {
                            ConverstationMessageId = PrevConMessages.Id;
                            RecentMsgTime          = PrevConMessages.CreatedTimeUTC;
                        }
                        else
                        {
                            RecentMsgTime = DateTime.Today.AddDays(-10);
                        }

                        LogProperties.info("Whats api after Conversation messages");

                        DateTime CurrentUtcNow = DateTime.UtcNow;
                        TimeSpan MessageSpan   = CurrentUtcNow - RecentMsgTime;


                        double totalSecForDay = 3 * 60 * 60;           // Static condiftion
                        bool   IsNewChat      = false;
                        if (MessageSpan.TotalSeconds > totalSecForDay) // create new conversations after 24 hours
                        {
                            Conversations conversations = new Conversations()
                            {
                                StatusId           = 1,
                                CustomerId         = CustomerId,
                                Mobile             = CustomerMobile,
                                ConversationTypeId = 2
                            };


                            ActionResult <Conversations> newCon = await conController.PostConversations(AccountId, WidgetId, conversations);

                            // JObject Con = await CreateConversation(AccountId, WidgetId, conversations);

                            OkObjectResult okResult = newCon.Result as OkObjectResult;

                            if (okResult.StatusCode == 200)
                            {
                                Conversations NewConversation = okResult.Value as Conversations;
                                ConverstationId = NewConversation.Id;
                            }



                            IsNewChat = true;
                        }
                        LogProperties.info("Whats api after Conversation save");
                        ConversationMessages conversationMessages = new ConversationMessages();
                        int IsBotEnd = 0;
                        //"MessageTypeId": "1",
                        //    "Message":msg
                        conversationMessages.ConversationId     = ConverstationId;
                        conversationMessages.MessageTypeId      = 1;
                        conversationMessages.ConversationTypeId = 2;

                        if (IsNewChat == false)
                        {
                            conversationMessages.AgentId = PrevConverstations.AgentId;
                        }
                        //message payload table
                        conversationMessages.Message = Convert.ToString(MessageJobj["payload"]["text"]);
                        string CustomerMessage = Convert.ToString(MessageJobj["payload"]["text"]);

                        string MessageType = Convert.ToString(MessageJobj["payload"]["type"]);


                        if (MessageType != "text")
                        {
                            //attachment

                            conversationMessages.AttachmentUrl = Convert.ToString(MessageJobj["payload"]["attachment"]);

                            conversationMessages.Message = ConstructMediaMessage(conversationMessages.AttachmentUrl, MessageType, conversationMessages.Message, ref MdeiaType);
                        }


                        var ConInfo = _context.ConversationInfo.Where(w => w.ConversationId == ConverstationId).FirstOrDefault();
                        if (ConInfo != null)
                        {
                            IsBotEnd = ConInfo.IsBotEnd;
                        }
                        if (IsBotEnd > 0)
                        {
                            conversationMessages.MessageTypeId = 3;
                        }
                        ActionResult <ConversationMessages> newConMsg = await conController.PostConversationMessages(AccountId, WidgetId, ConverstationId, IsBotEnd, conversationMessages);



                        OkObjectResult okResultMesg = newConMsg.Result as OkObjectResult;

                        if (okResultMesg.StatusCode == 200)
                        {
                            ConversationMessages NewConvMsg = okResultMesg.Value as ConversationMessages;
                        }

                        LogProperties.info("Whats api after Conversation message save");

                        if (IsBotEnd > 0)
                        {
                            // table for botend

                            //if (IsPingAgent == "true")
                            //{
                            //    cust_jsonObj = { "conversationId": conversationId, "from": conversationId, "to": agentId, "messageType": "0", "message": "Customer OnBoard" };
                            //}
                            //else
                            //{
                            //    cust_jsonObj = { "conversationId": conversationId, "from": fromId, "to": agentId, "messageType": "0", "message": "Customer OnBoard" };
                            //}
                            if (IsNewChat == false && IsBotEnd > 0) // send message to agent through socket
                            {
                                //JObject jobj = new JObject();
                                //jobj.Add(new JProperty("conversationId", conversationMessages.ConversationId));
                                //jobj.Add(new JProperty("from", "WhatsApp_"+ conversationMessages.ConversationId));
                                //jobj.Add(new JProperty("to", "Hub_" + conversationMessages.AgentId));
                                //jobj.Add(new JProperty("message", conversationMessages.Message));
                                //jobj.Add(new JProperty("messageType", "0"));

                                //WebSocketSubscriber.Send(jobj);

                                JObject jobjs        = new JObject();
                                JObject wsMessageObj = new JObject();


                                JObject CustomerDetails = new JObject();

                                //                "data":{"fromName" :"" ,"fromMobile",""}

                                CustomerDetails.Add(new JProperty("fromName", CustomerName));
                                CustomerDetails.Add(new JProperty("fromMobile", CustomerMobile));

                                jobjs.Add(new JProperty("conversationId", Convert.ToString(ConverstationId)));
                                jobjs.Add(new JProperty("from", "WhatsApp_5f2d3a8e31197a445686653b"));
                                jobjs.Add(new JProperty("to", "Hub_" + PrevConverstations.AgentId));
                                jobjs.Add(new JProperty("message", CustomerMessage));
                                jobjs.Add(new JProperty("mediaUrl", conversationMessages.AttachmentUrl));
                                jobjs.Add(new JProperty("type", MdeiaType));
                                jobjs.Add(new JProperty("data", CustomerDetails));
                                jobjs.Add(new JProperty("messageType", "0"));
                                jobjs.Add(new JProperty("ConversationTypeId", 2));

                                wsMessageObj = new JObject(new JProperty("Module", "Chat"),
                                                           new JProperty("Event", "NewChat"),
                                                           new JProperty("Channel_Name", "WhatsApp_Hub_" + PrevConverstations.AgentId),
                                                           new JProperty("Data", jobjs));


                                // WebSocketSubscriber wb = new WebSocketSubscriber();
                                WebSocketSubscriber.pushSocket(SocketPublishUrl, wsMessageObj);

                                LogProperties.info("Whats api after websocket publish");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogProperties.error("expection at WhatsApp Handler: " + ex.ToString());
            }
        }
예제 #11
0
        public override V3Message execute(Request message, RequestContext context)
        {
            object returnValue = null;

            switch (operation)
            {
            case SUBSCRIBE_OPERATION:
            {
                IDestination destObj =
                    ORBConfig.GetInstance().GetDataServices().GetDestinationManager().GetDestination(destination);
                Hashtable headers = new Hashtable();

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (destObj != null)
                {
                    String selectorName = (String)this.headers["DSSelector"];
                    String subtopic     = (String)this.headers["DSSubtopic"];
                    String dsId         = connection == null ? (String)this.headers["DSId"] : connection.GetHashCode().ToString();
                    String channel      = (String)this.headers["DSEndpoint"];

                    Subscriber subscriber = SubscriptionsManager.GetInstance().getSubscriber(
                        Subscriber.buildId(dsId, destObj.GetName(), subtopic, selectorName));

                    if (clientId == null || clientId.Equals(""))
                    {
                        clientId = Guid.NewGuid().ToString().ToUpper();
                    }

                    if (subscriber != null)
                    {
                        if (subscriber.addClient(clientId.ToString()))
                        {
                            destObj.GetServiceHandler().HandleSubscribe(subscriber, clientId.ToString(), this);
                        }

                        return(new AckMessage(messageId, clientId, null, headers));
                    }

                    object wsContext = ThreadContext.getProperties()[ORBConstants.WEB_SOCKET_MODE];

                    if (wsContext != null)
                    {
                        subscriber = new WebSocketSubscriber(selectorName, destObj, (UserContext)wsContext);
                    }
                    else if (connection != null)
                    {
                        subscriber = new DedicatedSubscriber(selectorName, destObj);
                        subscriber.setChannelId(RTMPHandler.getChannelId());
                        subscriber.setConnection(connection);
                    }
                    else
                    {
                        subscriber = SubscriberFactory.CreateSubscriber(channel, selectorName, destObj);
                    }

                    subscriber.setDSId(dsId);
                    subscriber.setSubtopic(subtopic);
                    subscriber.addClient((String)clientId);

                    try
                    {
                        SubscriptionsManager.GetInstance().AddSubscriber(dsId, destObj.GetName(), subscriber);
                    }
                    catch (Exception e)
                    {
                        if (Log.isLogging(LoggingConstants.EXCEPTION))
                        {
                            Log.log(LoggingConstants.EXCEPTION, e);
                        }
                    }

                    destObj.GetServiceHandler().HandleSubscribe(subscriber, clientId.ToString(), this);
                }
                else
                {
                    String error = "Unknown destination " + destination + ". Cannot handle subscription request";

                    if (Log.isLogging(LoggingConstants.ERROR))
                    {
                        Log.log(LoggingConstants.ERROR, error);
                    }

                    return(new ErrMessage(messageId, new Exception(error)));
                }

                return(new AckMessage(messageId, clientId, null, headers));
            }
            break;

            case UNSUBSCRIBE_OPERATION:
            {
                String subtopic     = (String)this.headers["DSSubtopic"];
                String dsId         = (String)this.headers["DSId"];
                String selectorName = (String)this.headers["DSSelector"];

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (connection != null)
                {
                    dsId = connection.GetHashCode().ToString();
                }

                Subscriber subscriber = SubscriptionsManager.GetInstance().getSubscriber(
                    Subscriber.buildId(dsId, destination, subtopic, selectorName));

                if (subscriber != null)
                {
                    SubscriptionsManager.GetInstance().unsubscribe(subscriber, clientId.ToString(), this);
                }
            }
            break;

            case DISCONNECT_OPERATION:
            {
                String         dsId       = (String)this.headers["DSId"];
                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (connection != null)
                {
                    dsId = connection.GetHashCode().ToString();
                }

                SubscriptionsManager subscriptionsManager = SubscriptionsManager.GetInstance();
                List <Subscriber>    subscribers          = subscriptionsManager.getSubscribersByDsId(dsId);

                if (subscribers != null)
                {
                    foreach (Subscriber subscriber in subscribers)
                    {
                        if (subscriber != null)
                        {
                            subscriptionsManager.unsubscribe(subscriber, this);
                        }
                    }
                }

                subscriptionsManager.removeSubscriber(dsId);
            }
            break;

            case POLL_OPERATION:
            {
                String dsId = (String)this.headers["DSId"];

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (connection != null)
                {
                    dsId = connection.GetHashCode().ToString() + "";
                }

                try
                {
                    WebORBArray <V3Message> messages =
                        new WebORBArray <V3Message>(SubscriptionsManager.GetInstance().getMessages(dsId));

                    if (messages.Count == 0)
                    {
                        return(new AckMessage(null, null, null, new Hashtable()));
                    }

                    return(new CommandMessage(CLIENT_SYNC_OPERATION, messages));
                }
                catch (Exception e)
                {
                    String error = "Invalid client id " + dsId;

                    if (Log.isLogging(LoggingConstants.ERROR))
                    {
                        Log.log(LoggingConstants.ERROR, error, e);
                    }

                    return(new ErrMessage(messageId, new Exception(error)));
                }
            }
            break;

            case CLIENT_PING_OPERATION:
            {
                Hashtable headers = new Hashtable();

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();
                if (connection != null)
                {
                    headers.Add("DSId", connection.GetHashCode().ToString());
                }
                else
                {
                    headers.Add("DSId", Guid.NewGuid().ToString().ToUpper());
                }

                return(new AckMessage(messageId, clientId, null, headers));
            }
            break;

            case LOGOUT_OPERATION:
            {
                ThreadContext.setCallerCredentials(null, null);
                Thread.CurrentPrincipal = null;
            }
            break;

            case LOGIN_OPERATION:
            {
                String credentials = (String)((IAdaptingType)((object[])body.body)[0]).defaultAdapt();
                byte[] bytes       = Convert.FromBase64String(credentials);
                credentials = new String(Encoding.UTF8.GetChars(bytes));
                IAuthenticationHandler authHandler = ORBConfig.GetInstance().getSecurity().GetAuthenticationHandler();

                if (authHandler == null)
                {
                    ErrMessage errorMessage = new ErrMessage(messageId, new ServiceException("Missing authentication handler"));
                    errorMessage.faultCode = "Client.Authentication";
                    return(errorMessage);
                }

                int    index    = credentials.IndexOf(":");
                string userid   = null;
                string password = null;

                if (index != -1 && index != 0 && index != credentials.Length - 1)
                {
                    userid   = credentials.Substring(0, index);
                    password = credentials.Substring(index + 1);

                    try
                    {
                        IPrincipal principal = authHandler.CheckCredentials(userid, password, message);

                        try
                        {
                            Thread.CurrentPrincipal = principal;
                            ThreadContext.currentHttpContext().User = principal;
                        }
                        catch (Exception exception)
                        {
                            if (Log.isLogging(LoggingConstants.ERROR))
                            {
                                Log.log(LoggingConstants.ERROR,
                                        "Unable to set current principal. Make sure your current permission set allows Principal Control",
                                        exception);
                            }

                            throw exception;
                        }

                        Credentials creds = new Credentials();
                        creds.userid   = userid;
                        creds.password = password;
                        ThreadContext.setCallerCredentials(creds, principal);
                    }
                    catch (Exception exception)
                    {
                        ErrMessage errorMessage = new ErrMessage(messageId, exception);
                        errorMessage.faultCode = "Client.Authentication";
                        return(errorMessage);
                    }
                }
                else
                {
                    ErrMessage errorMessage = new ErrMessage(messageId, new ServiceException("Invalid credentials"));
                    errorMessage.faultCode = "Client.Authentication";
                    return(errorMessage);
                }
            }
            break;
            }

            return(new AckMessage(messageId, clientId, returnValue, new Hashtable()));
        }