Пример #1
0
 /// <summary>
 /// Gets connected users list formatted for chat output
 /// </summary>
 /// <param name="context">Hub context</param>
 /// <param name="clients">Client collection</param>
 /// <returns>User list formatted string</returns>
 public string GetUsersListString(HubCallerContext context, IHubCallerClients clients)
 {
     lock (Users)
     {
         return(string.Join('\n', Users.Select(u => u.Value)));
     }
 }
Пример #2
0
        public async Task Ping(IHubCallerClients clients, PingPongMessage receivedPing)
        {
            _repository.save(receivedPing);

            _logger.log("Sleeping for " + PING_PONG_INTERVAL + " milliseconds");
            Thread.Sleep(PING_PONG_INTERVAL);

            PingPongMessage pongResponse = new PingPongMessage();

            pongResponse.date      = System.DateTime.UtcNow.ToString();
            pongResponse.messageId = receivedPing.messageId + 1;

            if (receivedPing.sessionId == Guid.Empty)
            {
                pongResponse.sessionId = Guid.NewGuid();
                _logger.log("No session specified for incoming ping; new Session ID: " + pongResponse.sessionId.ToString());
            }
            else
            {
                pongResponse.sessionId = receivedPing.sessionId;
            }

            _logger.log("Sending pong with Session ID: " + pongResponse.sessionId.ToString() + " & Message ID: " + pongResponse.messageId.ToString());

            await clients.Caller.SendAsync("pong", pongResponse);

            _repository.save(pongResponse);
        }
Пример #3
0
        public async Task SendInfoAsync(string channel, int value)
        {
            IHubCallerClients clients = this.Clients;

            if (clients == null)
            {
                Console.WriteLine("no clients yet");
            }
            else
            {
                string[] conn;
                lock (this.connections)
                    conn = connections.ToArray();

                if (conn != null)
                {
                    await clients.Clients(conn).SendAsync(channel, value);

                    Console.WriteLine($"Sent {value} via {channel} to {conn.Length}");
                }
                else
                {
                    Console.WriteLine("Skipping sending, connection null");
                }
            }
        }
Пример #4
0
        public async Task <bool> Handle(HubCallerContext context, IHubCallerClients clients, string message)
        {
            //todo Should store message for later
            await clients.All.SendAsync("ReceiveMessage", DateTime.Now.ToString("G"), _chatService.GetName(context), message);

            return(true);
        }
        public void StartManagement(IHubCallerClients clients)
        {
            if (_isStarted)
            {
                return;
            }

            var ruleModels = _ruleService.GetRules();

            Observable.Interval(TimeSpan.FromSeconds(1))
            .Timestamp()
            .Subscribe(async i =>
            {
                var plantModels = _plantService.GetAllPlants();
                foreach (var plant in plantModels)
                {
                    var rule         = ruleModels.FirstOrDefault(r => r.CurrentStatus == plant.Status);
                    var timeToCopare = (rule?.TimeCalcTarget == TimeTarget.LASTUPDATE)
                            ? plant.LastUpdate
                            : plant.LastWaterSession;
                    if (rule != null && DateTime.Compare(i.Timestamp.LocalDateTime, timeToCopare.Add(rule.Time)) > 0)
                    {
                        plant.LastUpdate = i.Timestamp.LocalDateTime;
                        plant.Status     = rule.NextStatus;
                        _plantService.UpdatePlant(plant);

                        await clients.All.SendAsync("StatusUpdate", plant.Id, plant.Status, plant.LastUpdate);
                    }
                }
            });

            _isStarted = true;
        }
Пример #6
0
        /// <summary>
        /// Delete a shape from a Canvas
        /// </summary>
        /// <param name="Context">SignalR context</param>
        /// <param name="Clients">SignalR clients</param>
        /// <param name="shapeIDString">Shape ID (sent by the client)</param>
        /// <returns></returns>
        public static async Task DeleteShape(HubCallerContext Context, IHubCallerClients Clients, string shapeIDString)
        {
            string id        = Context.ConnectionId;
            string sessionId = User.ConnectionIdSessionIdTranslationTable[id];

            uint  shapeID = uint.Parse(shapeIDString);
            User  user    = User.Users[sessionId];
            Lobby lobby   = Lobby.Lobbies[user.Lobby];

            var deletedShape = lobby.Canvas.Shapes[shapeID];

            if ((deletedShape.Owner.OverridePermissions >> 1 != deletedShape.OverrideUserPolicy >> 1) || deletedShape.Owner == user)
            {
                lobby.Canvas.Shapes.Remove(deletedShape.ID);

                lobby.Canvas.Serialize();
                SQLiteConnection db = new SQLiteConnection("database.db");
                db.Update(lobby.Canvas);

                await Clients.Group(lobby.GroupName).SendAsync("deleteShape", deletedShape.ID);
            }
            else
            {
                await Clients.Caller.SendAsync("deleteShape", null);
            }
        }
Пример #7
0
        /// <summary>
        /// Update shape's permissions (allow or deny shape updating or deletion)
        /// </summary>
        /// <param name="Context">SignalR context</param>
        /// <param name="Clients">SignalR clients</param>
        /// <param name="shapeIDString">Shape ID (sent by the client)</param>
        /// <param name="permission">New permissions (0 to 3: 1st bit is Update and 2nd is Delete)</param>
        /// <returns></returns>
        public static async Task UpdateShapePermission(HubCallerContext Context, IHubCallerClients Clients, string shapeIDString, string permission)
        {
            string id        = Context.ConnectionId;
            string sessionId = User.ConnectionIdSessionIdTranslationTable[id];

            uint  shapeID       = uint.Parse(shapeIDString);
            byte  newPermission = byte.Parse(permission);
            User  user          = User.Users[sessionId];
            Lobby lobby         = Lobby.Lobbies[user.Lobby];
            var   Shape         = lobby.Canvas.Shapes[shapeID];

            if (Shape.Owner == user)
            {
                Shape.OverrideUserPolicy = newPermission;

                SQLiteConnection db = new SQLiteConnection("database.db");
                db.Update(lobby.Canvas);

                await Clients.Group(lobby.GroupName).SendAsync("newShapePermission", Shape.ID, Shape.OverrideUserPolicy);
            }
            else
            {
                await Clients.Caller.SendAsync("newShapePermission", null, null);
            }
        }
Пример #8
0
        /// <summary>
        /// Update a shape in a Canvas
        /// </summary>
        /// <param name="Context">SignalR context</param>
        /// <param name="Clients">SignalR clients</param>
        /// <param name="shapeType">Shape code (see ShapeCode enum)</param>
        /// <param name="newShape">JSON formatted string</param>
        /// <returns></returns>
        public static async Task UpdateShape(HubCallerContext Context, IHubCallerClients Clients, string shapeType, string newShape)
        {
            string id        = Context.ConnectionId;
            string sessionId = User.ConnectionIdSessionIdTranslationTable[id];

            User  user         = User.Users[sessionId];
            Lobby lobby        = Lobby.Lobbies[user.Lobby];
            Shape updatedShape = GetShapeFromJSON(byte.Parse(shapeType), newShape);
            Shape oldShape     = lobby.Canvas.Shapes[updatedShape.ID];

            if (((oldShape.Owner.OverridePermissions & 1) != (oldShape.OverrideUserPolicy & 1)) || oldShape.Owner == user)
            {
                oldShape.UpdateWithNewShape(updatedShape);

                lobby.Canvas.Serialize();
                SQLiteConnection db = new SQLiteConnection("database.db");
                db.Update(lobby.Canvas);

                await Clients.Group(lobby.GroupName).SendAsync("updateShape", shapeType, oldShape);
            }
            else
            {
                await Clients.Caller.SendAsync("updateShape", null, null);
            }
        }
Пример #9
0
        public async Task SendChatMesssage(string name, string message, IHubCallerClients clients, string callersUserName)
        {
            string id = GetConnectionId(name);
            ChatMessageViewModel model = await GenerateChatMessage(message, name, callersUserName);

            await clients.Client(id).SendAsync("ReceiveChatMessage", model);
        }
Пример #10
0
 public void Register()
 {
     if (globalClients == null)
     {
         globalClients = Clients;
         SendTime();
     }
 }
Пример #11
0
 public static void Init(IHubCallerClients clients, Topology topology)
 {
     if (_instance == null)
     {
         signalrClients = clients;
         _instance      = new MachineWatcher(topology);
     }
 }
Пример #12
0
        public override async Task OnConnectedAsync()
        {
            var idUsuario = Context.GetHttpContext().Request.Query["idUsuario"];
            await _repositorio.AddAsync(new HubEntidade(idUsuario, Context.ConnectionId, HubType.EmailEnviadosColeta));

            _clients = Clients;
            await base.OnConnectedAsync();
        }
 public WatsonChatConversation(
     IMessageHubManager messageHubManager,
     IHubCallerClients clientsManager,
     IUserTracker <HubWithPresence> userTracker,
     UOW uow)
     : base(messageHubManager, clientsManager, userTracker, uow)
 {
 }
Пример #14
0
 public void SetBasics(IHubCallerClients clients, IConfiguration configuration, string myGuid,
                       CancellationTokenSource cancellation, string connectionId)
 {
     _signalrClients = clients;
     _configuration  = configuration;
     _myGuid         = myGuid;
     _cancellation   = cancellation;
     _connectionId   = connectionId;
 }
Пример #15
0
 public DefaultMessageHubManager(
     HubCallerContext hubContext,
     IHubCallerClients clientsManager,
     IMessageLogger messageLogger)
 {
     this.hubContext     = hubContext ?? throw new ArgumentNullException(nameof(hubContext));
     this.clientsManager = clientsManager ?? throw new ArgumentNullException(nameof(clientsManager));
     this.messageLogger  = messageLogger ?? throw new ArgumentNullException(nameof(messageLogger));
 }
Пример #16
0
        internal static Task InternalSend(IHubCallerClients clients, string channel, object data)
        {
            var messageId = Guid.NewGuid();
            var timestamp = DateTime.Now;

            Message?.Invoke(messageId, timestamp, channel, data);

            return(clients.All.SendAsync(CLIENT_METHOD_NAME, new { guid = messageId, timestamp, channel, data }));
        }
Пример #17
0
 public async Task SendGameStateToUsersInGame(GameStateModel game, IHubCallerClients clients)
 {
     foreach (Player player in game.Players)
     {
         if (_nameValidator.IsValidUserName(player.UserName))
         {
             await _sender.SendGameState(player.UserName, game, clients);
         }
     }
 }
Пример #18
0
        /// <summary>
        /// Get SVG from a Canvas
        /// </summary>
        /// <param name="Context">SignalR context</param>
        /// <param name="Clients">SignalR clients</param>
        /// <returns></returns>
        public static async Task GetSVG(HubCallerContext Context, IHubCallerClients Clients)
        {
            string id        = Context.ConnectionId;
            string sessionId = User.ConnectionIdSessionIdTranslationTable[id];

            User  user  = User.Users[sessionId];
            Lobby lobby = Lobby.Lobbies[user.Lobby];

            await Clients.Caller.SendAsync("SVG", lobby.Canvas.ToSVG());
        }
Пример #19
0
        public IGameCore GetGameCore(string gameId, IHubCallerClients clients)
        {
            IGameCore gameCore;

            _gameCores.TryGetValue(gameId, out gameCore);
            if (gameCore != null && gameCore.Clients == null)
            {
                gameCore.Clients = clients;
            }
            return(gameCore);
        }
Пример #20
0
        public async Task <bool> Handle(HubCallerContext context, IHubCallerClients clients, string message)
        {
            if (!message.Equals("/users", StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            await clients.Caller.SendAsync("ReceiveMessage", DateTime.Now.ToString("G"), null, $"Users:\n{_chatService.GetUsersListString(context, clients)}");

            return(true);
        }
Пример #21
0
        /// <summary>
        /// Notifications when user joins chat
        /// Could be done in OnConnectedAsync event
        /// </summary>
        /// <param name="context">Hub context</param>
        /// <param name="clients">Client collection</param>
        public async Task UserJoinedAsync(HubCallerContext context, IHubCallerClients clients)
        {
            // Get current user name
            var name = GetName(context);

            // Notify other users that someone is here
            await clients.Others.SendAsync("ReceiveMessage", DateTime.Now.ToString("G"), null, $"{name} came to scare us!");

            // Notify current user that we are ready
            await clients.Caller.SendAsync("ReceiveMessage", DateTime.Now.ToString("G"), name, "Lock and loaded!");
        }
 public async Task SendMessageAsync(string message)
 {
     if (Clients != null)
     {
         Client = Clients;
     }
     if (Client != null)
     {
         await Client.All.SendAsync("SendMessage", message);
     }
 }
Пример #23
0
 public async Task HandleAdminLiveMessage(
     AdminGroupLiveMessageModel adminGroupLiveMessageModel,
     GoLiveDto goLiveDto, Server dbContext,
     UserManager <IdentityUser> userManager, IHubCallerClients clients
     )
 {
     await clients.Group(goLiveDto.UserTeamGroup)
     .SendAsync("RecieveCommentary",
                JsonConvert.SerializeObject(adminGroupLiveMessageModel)
                );
 }
Пример #24
0
 public Room(string roomName, User firstUser, IHubCallerClients clients)
 {
     this.Clients    = clients;
     this.RoomId     = Guid.NewGuid().ToString();
     this.RoomName   = roomName;
     this.RoomStatus = (int)Status.Waiting;
     this.PlayerList = new List <User> {
         firstUser
     };
     this.GuestList  = new List <User>();
     this.ReadyArray = new bool[2];
 }
 public DefaultConversationHandler(
     IMessageHubManager messageHubManager,
     IHubCallerClients clientsManager,
     IUserTracker <HubWithPresence> userTracker,
     UOW uow
     )
 {
     this.messageHubManager = messageHubManager ?? throw new System.ArgumentNullException(nameof(messageHubManager));
     this.clientsManager    = clientsManager ?? throw new System.ArgumentNullException(nameof(clientsManager));
     this.userTracker       = userTracker ?? throw new System.ArgumentNullException(nameof(userTracker));
     this.uow = uow ?? throw new System.ArgumentNullException(nameof(uow));
 }
Пример #26
0
        public async Task MessageSend(IHubCallerClients clients, chatMessageRequest userInfoRequest)
        {
            var response = new chatMessageResponse()
            {
                SelfconnetionId = userInfoRequest.SelfconnetionId,
                MsgType         = messageTypes.All,
                Message         = userInfoRequest.Message
            };


            var outputBuffer = new ArraySegment <byte>(response.ToByteArray(), 0, (int)response.ToByteArray().Length);
            await clients.All.SendAsync("brocaste", outputBuffer);
        }
Пример #27
0
 public AgentHubRules(
     LivechatRules livechatRules,
     IUserTracker <MktChatHub> userTracker,
     IGroupManager groupManager,
     IHubCallerClients clientsManager,
     IChatConversationHandler conversationHandler
     )
 {
     this.livechatRules       = livechatRules ?? throw new System.ArgumentNullException(nameof(livechatRules));
     this.userTracker         = userTracker ?? throw new System.ArgumentNullException(nameof(userTracker));
     this.groupManager        = groupManager ?? throw new System.ArgumentNullException(nameof(groupManager));
     this.clientsManager      = clientsManager ?? throw new System.ArgumentNullException(nameof(clientsManager));
     this.conversationHandler = conversationHandler ?? throw new System.ArgumentNullException(nameof(conversationHandler));
 }
        public async Task RemoveGameIfEmpty(GameStateModel game, IHubCallerClients clients)
        {
            string[] playerNames = new string[] { game.Players[0].UserName, game.Players[1].UserName };

            if (_nameValidator.IsGameEmpty(playerNames))
            {
                _memoryAccess.RemoveGameFromMemory(game.GameId);
            }
            else
            {
                _memoryAccess.UpdateGame(game);
                await _messenger.SendGameStateToUsersInGame(game, clients);
            }
        }
 public HumanAgentConversation(
     IMessageHubManager messageHubManager,
     IHubCallerClients clientsManager,
     IUserTracker<HubWithPresence> userTracker,
     UOW uow,
     PushNotificationService pushNotificationService
 ) : base(
         messageHubManager, 
         clientsManager, 
         userTracker, 
         uow
     )
 {
     this.pushNotificationService = pushNotificationService ?? throw new System.ArgumentNullException(nameof(pushNotificationService));
 }
 /// <inheritdoc />
 public HubConnectionMessageContext(
     [JetBrains.Annotations.NotNull] IConnectionService connectionService,
     [JetBrains.Annotations.NotNull] IPeerPayloadSendService <object> payloadSendService,
     [JetBrains.Annotations.NotNull] IPeerRequestSendService <object> requestSendService,
     [JetBrains.Annotations.NotNull] IGroupManager groups,
     [JetBrains.Annotations.NotNull] IHubCallerClients <TRemoteClientHubType> clients,
     [JetBrains.Annotations.NotNull] HubCallerContext hubConntext)
 {
     ConnectionService  = connectionService ?? throw new ArgumentNullException(nameof(connectionService));
     PayloadSendService = payloadSendService ?? throw new ArgumentNullException(nameof(payloadSendService));
     RequestSendService = requestSendService ?? throw new ArgumentNullException(nameof(requestSendService));
     Groups             = groups ?? throw new ArgumentNullException(nameof(groups));
     Clients            = clients ?? throw new ArgumentNullException(nameof(clients));
     HubConntext        = hubConntext ?? throw new ArgumentNullException(nameof(hubConntext));
 }