コード例 #1
0
ファイル: Notify.cs プロジェクト: hjsmwz/Notify.Me
        public override async Task OnConnectedAsync()
        {
            try
            {
                var name            = Context.User.Identity.Name;
                var response        = Context.GetHttpContext().Response;
                var fromUrl         = response.Headers["Access-Control-Allow-Origin"];
                var isHostConnected = false;
                var key             = Context.GetHttpContext().Request.Query["key"];
                _logger.LogDebug($"Connecting with Access Key:{key}...");

                if (!_visitor.HasVisitorAccess(fromUrl, key))
                {
                    throw new HubException("Invalid access key for the origin. Please check your access key");
                }


                if (string.IsNullOrEmpty(name))
                {
                    //Monitor usage example
                    if (Monitor.TryEnter(_syncObject, _timeoutWait))
                    {
                        try
                        {
                            var userId = _random.Next(0, 10);
                            name = $"WebUser{userId.ToString()}";
                        }
                        finally
                        {
                            Monitor.Exit(_syncObject);
                        }
                    }
                    else
                    {
                        _logger.LogDebug("Can not assign name");
                    }
                }
                else
                {
                    name = _configuration["HostUser:Name"];
                    await Clients.All.SendAsync("SayHello", "online");

                    isHostConnected = true;
                }
                _visitor.LetInVisitor(Context.ConnectionId ?? Guid.NewGuid().ToString(), name, fromUrl);
                _logger.LogDebug($"{name} is connected.");

                var host = _db.Connections.Where(c => c.User.UserName == _configuration["HostUser:Name"] && c.Connected)
                           .OrderByDescending(c => c.ConnectionDate)
                           .FirstOrDefault();

                await Clients.Caller.SendAsync("GiveName", name);

                if (!isHostConnected)
                {
                    await SendWelcomeMessage(new ChatMessage()
                    {
                        Message          = "How can I help you?",
                        Username         = _configuration["HostUser:Name"],
                        FriendlyUsername = _configuration["HostUser:Name"],
                    });
                }

                if (host != null)
                {
                    _logger.LogDebug($"Host{ host.ConnectionID} is already connected. Informing host...");
                    await Clients.Client(host.ConnectionID).SendAsync("iamin", name);
                }
                await base.OnConnectedAsync();
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, $"Connection failed: {ex.Message}");
                throw ex;
            }
        }