public void TestCreateUserIfNotExistsWithNoExistingUser()
        {
            string    channelId = "C12345";
            string    userId    = "U12345";
            string    username  = "******";
            SlackUser user      = new SlackUser(userId, username);

            ScoreInfo capturedScoreInfo = null;

            scoreInfoRepository.Setup(x => x.FindByChannelIdAndUserId(It.IsAny <string>(), It.IsAny <string>())).Returns((ScoreInfo)null);
            scoreInfoRepository.Setup(x => x.Save(It.IsAny <ScoreInfo>())).Callback <ScoreInfo>(si => capturedScoreInfo = si);

            bool result = cut.CreateUserIfNotExists(channelId, user);

            Assert.IsTrue(result);

            scoreInfoRepository.Verify(x => x.FindByChannelIdAndUserId(channelId, userId));
            scoreInfoRepository.Verify(x => x.Save(It.IsAny <ScoreInfo>()));

            Assert.IsNotNull(capturedScoreInfo);
            Assert.AreEqual(channelId, capturedScoreInfo.ChannelId);
            Assert.AreEqual(userId, capturedScoreInfo.UserId);
            Assert.AreEqual(username, capturedScoreInfo.Username);
            Assert.AreEqual(0L, capturedScoreInfo.Score);
        }
Beispiel #2
0
        public SlackResponseDoc Join(SlackRequestDoc requestDoc)
        {
            SlackUser user        = new SlackUser(requestDoc.UserId, requestDoc.Username);
            bool      userCreated = _scoreService.CreateUserIfNotExists(requestDoc.ChannelId, user);

            SlackResponseDoc responseDoc = new SlackResponseDoc
            {
                ResponseType = SlackResponseType.EPHEMERAL
            };

            if (userCreated)
            {
                responseDoc.Text = "Joining game.";

                SlackResponseDoc delayedResponseDoc = new SlackResponseDoc
                {
                    ResponseType = SlackResponseType.IN_CHANNEL,
                    Text         = String.Format("<@{0}> has joined the game!", user.UserId)
                };

                _delayedSlackService.sendResponse(requestDoc.ResponseUrl, delayedResponseDoc);
            }
            else
            {
                responseDoc.Text = "You're already in the game.";
            }

            return(responseDoc);
        }
        static IServiceContainer CompositionRoot(string slackToken, SlackUser adminUser, FaceDetectionConfiguration faceDetectionConfiguration, BlobStorageConfiguration blobStorageConfiguration)
        {
            var serviceContainer = new ServiceContainer();

            serviceContainer.RegisterInstance(slackToken);
            serviceContainer.RegisterInstance(adminUser);

            if (string.IsNullOrEmpty(faceDetectionConfiguration.Key))
            {
                serviceContainer.Register <IFaceDetectionClient, FaceServiceClientDummy>();
                serviceContainer.Register <IFaceWhitelist, FaceWhitelistDummy>();
            }
            else
            {
                serviceContainer.RegisterInstance(faceDetectionConfiguration);
                serviceContainer.RegisterInstance <IFaceServiceClient>(new FaceServiceClient(faceDetectionConfiguration.Key, faceDetectionConfiguration.URL));
                serviceContainer.Register <IFaceDetectionClient, FaceDetectionClient>();
                serviceContainer.RegisterInstance <IFaceWhitelist>(new FaceWhitelist(blobStorageConfiguration));
            }

            serviceContainer.Register <ISlackProfileValidator, SlackProfileValidator>();
            serviceContainer.Register <ISlackConnector, SlackConnector.SlackConnector>();
            serviceContainer.Register <ISlackIntegration, SlackIntegration>();
            serviceContainer.Register <ProfilebotImplmentation>();

            return(serviceContainer);
        }
Beispiel #4
0
        private async Task should_not_raise_event_given_missing_user_info(Mock <IWebSocketClient> webSocket, SlackConnection slackConnection)
        {
            // given
            var connectionInfo = new ConnectionInformation {
                WebSocket = webSocket.Object
            };
            await slackConnection.Initialise(connectionInfo);

            SlackUser lastUser = null;

            slackConnection.OnUserJoined += user =>
            {
                lastUser = user;
                return(Task.CompletedTask);
            };

            var inboundMessage = new UserJoinedMessage
            {
                User = new User
                {
                    Id = null
                }
            };

            // when
            webSocket.Raise(x => x.OnMessage += null, null, inboundMessage);

            // then
            lastUser.ShouldBeNull();
            slackConnection.UserCache.ShouldBeEmpty();
        }
Beispiel #5
0
        protected override void Given()
        {
            base.Given();

            SUT.OnUserJoined += user =>
            {
                _lastUser = user;
                return(Task.FromResult(false));
            };

            InboundMessage = new UserJoinedMessage
            {
                MessageType = MessageType.Team_Join,
                User        = new User
                {
                    Id             = "some-id",
                    Name           = "my-name",
                    TimeZoneOffset = -231,
                    IsBot          = true,
                    Presence       = "active"
                }
            };

            _expectedUser = new SlackUser
            {
                Id             = "some-id",
                Name           = "my-name",
                TimeZoneOffset = -231,
                IsBot          = true,
                Online         = true
            };
        }
Beispiel #6
0
        public void GetUserIdForEmail_MultipleUsersWithEmailSet_ReturnsCorrectUser()
        {
            // given
            var slackUser1 = new SlackUser()
            {
                Id    = "ABC",
                Email = "*****@*****.**"
            };
            var slackUser2 = new SlackUser()
            {
                Id    = "DEF",
                Email = "*****@*****.**"
            };
            var slackUser3 = new SlackUser()
            {
                Id    = "QWE",
                Email = "*****@*****.**"
            };

            var userCache = new ReadOnlyDictionary <string, SlackUser>(new Dictionary <string, SlackUser>
            {
                { slackUser1.Id, slackUser1 },
                { slackUser2.Id, slackUser2 },
                { slackUser3.Id, slackUser3 },
            });


            // when
            var result = userCache.FindByEmail("*****@*****.**");

            // then
            result.Id.ShouldBe("ABC");
        }
        /// <summary>
        ///     Checks whether a given user is whitelisted.
        /// </summary>
        /// <param name="user">The Slack user to check.</param>
        /// <returns>Whether the given user is whitelisted.</returns>
        public async Task <bool> IsUserWhitelisted(SlackUser user)
        {
            user.Guard();
            await InitializeWhitelistIfNeeded();

            return(whitelistedUserIds.Contains(user.Id));
        }
 public static SlackMessage CreateMessage(SlackUser sender, string messageText) =>
 new SlackMessage
 {
     User = sender, Text = messageText, ChatHub = new SlackChatHub {
         Type = SlackChatHubType.DM
     }
 };
Beispiel #9
0
        /// <summary>
        /// Validates that a user profile is complete.
        /// </summary>
        /// <param name="user">The user to be validated.</param>
        /// <returns>The result of the validation.</returns>
        public ProfileValidationResult ValidateProfile(SlackUser user)
        {
            Verify(user);

            var errors = new StringBuilder();

            ValidateEmail(user, errors);

            if (string.IsNullOrEmpty(user.FirstName))
            {
                errors.AppendLine("Fornavn må registreres slik at folk vet hvem du er.");
            }

            if (string.IsNullOrEmpty(user.LastName))
            {
                errors.AppendLine("Etternavn må registreres slik at folk vet hvem du er.");
            }

            if (string.IsNullOrEmpty(user.WhatIDo))
            {
                errors.AppendLine("Feltet \"What I do\" må inneholde team og hva du kan i DIPS.");
            }

            ValidateProfileImage(user, errors);

            var actualErrors = errors.ToString();

            return(actualErrors.Length == 0 || user.IsBot || user.Deleted || user.Name == "slackbot"
                ? new ProfileValidationResult(true, null, null)
                : new ProfileValidationResult(false, user.Id,
                                              $"Hei <@{user.Id}>, jeg har sett gjennom profilen din og den har følgende mangler:" +
                                              $"{Environment.NewLine}{actualErrors}{Environment.NewLine}" +
                                              "Se https://utvikling/t/slack/1822 for hva som kreves av en fullt utfylt profil." +
                                              $"{Environment.NewLine}Ta kontakt med <@{adminUserId}> dersom du har spørsmål."));
        }
Beispiel #10
0
 static void ValidateProfileImage(SlackUser user, StringBuilder errors)
 {
     if (string.IsNullOrEmpty(user.Image))
     {
         errors.AppendLine("Legg inn et profilbilde slik at folk kjenner deg igjen.");
     }
 }
Beispiel #11
0
        public static SlackUser ToSlackUser(this User user)
        {
            var slackUser = new SlackUser
            {
                Id             = user.Id,
                Name           = user.Name,
                Email          = user.Profile?.Email,
                TimeZoneOffset = user.TimeZoneOffset,
                IsBot          = user.IsBot,
                FirstName      = user.Profile?.FirstName,
                LastName       = user.Profile?.LastName,
                Image          = user.Profile?.Image,
                WhatIDo        = user.Profile?.Title,
                Deleted        = user.Deleted,
                IsGuest        = user.IsGuest,
                StatusText     = user.Profile?.StatusText,
                IsAdmin        = user.IsAdmin
            };

            if (!string.IsNullOrWhiteSpace(user.Presence))
            {
                slackUser.Online = user.Presence == "active";
            }

            return(slackUser);
        }
        private Dictionary <string, SlackUser> GenerateUsers(HandshakeResponse handshakeResponse)
        {
            var users = new Dictionary <string, SlackUser>();

            foreach (var user in handshakeResponse.Users)
            {
                var slackUser = new SlackUser
                {
                    Id    = user.Id,
                    Name  = user.Name,
                    IsBot = false,
                    Icons = user.Profile?.Icons
                };
                users.Add(user.Id, slackUser);
            }

            foreach (var bot in handshakeResponse.Bots)
            {
                var slackUser = new SlackUser
                {
                    Id    = bot.Id,
                    Name  = bot.Name,
                    IsBot = true,
                    Icons = bot.Icons
                };
                users.Add(bot.Id, slackUser);
            }

            return(users);
        }
Beispiel #13
0
        public async Task <SlackMessage> SendMessageAsync(SlackChannel channel, SlackUser user, string text, params SlackAttachment[] attachments)
        {
            List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(new KeyValuePair <string, string>("channel", channel.Id));
            parameters.Add(new KeyValuePair <string, string>("text", text));
            parameters.Add(new KeyValuePair <string, string>("as_user", "true"));

            if (attachments.Length > 0)
            {
                parameters.Add(new KeyValuePair <string, string>("attachments", JArray.FromObject(attachments).ToString(Formatting.None)));
            }

            var result = await GetApiDataProperty <SlackMessage>(ApiCommands.Message, "message", new string[] { "user", "channel" }, parameters.ToArray());

            if (result == default(SlackMessage))
            {
                return(default(SlackMessage));
            }
            result.SetApi(this);
            result.Timestamp = DateTime.UtcNow;
            result.Channel   = channel;
            result.User      = user;
            return(result);
        }
 ProfileValidationResult(bool isValid, SlackUser user, string errors, Uri imageURL)
 {
     user.Guard();
     IsValid  = isValid;
     User     = user;
     Errors   = errors;
     ImageURL = imageURL;
 }
 /// <summary>
 ///     Constructs a result of a profile that failed validation.
 /// </summary>
 /// <param name="user">The Slack user to which this result belongs.</param>
 /// <param name="errors">The errors found.</param>
 /// <param name="imageURL">Has value if the user's profile image is invalid.</param>
 public ProfileValidationResult(SlackUser user, string errors, Uri imageURL = null) :
     this(false, user, errors, imageURL)
 {
     if (string.IsNullOrEmpty(errors))
     {
         throw new ArgumentException(nameof(errors));
     }
 }
Beispiel #16
0
        public void Add(SlackUser slackUser)
        {
            var user = new User {
                Id = slackUser.Id, DisplayName = slackUser.Profile.FirstName, Username = slackUser.Name
            };

            _dictionary.AddOrUpdate(slackUser.Id, user, (k, v) => user);
        }
        async Task WhitelistProfile(SlackUser user)
        {
            await slackIntegration.IndicateTyping(adminUser);

            await faceWhitelist.WhitelistUser(user);

            await slackIntegration.SendDirectMessage(adminUser, $"Whitelisted {user.FormattedUserId}");
        }
Beispiel #18
0
 public bool CanRespond(Message message, SlackUser user)
 {
     return
         (message.text.StartsWith("?", StringComparison.OrdinalIgnoreCase) ||
          message.text.StartsWith("help", StringComparison.OrdinalIgnoreCase) ||
          message.text.StartsWith("what?", StringComparison.OrdinalIgnoreCase) ||
          message.text.StartsWith("what can I", StringComparison.OrdinalIgnoreCase));
 }
Beispiel #19
0
        private Task HandleUserJoined(UserJoinedMessage inboundMessage)
        {
            SlackUser slackUser = inboundMessage.User.ToSlackUser();

            this._userCache[slackUser.Id] = slackUser;

            return(this.RaiseUserJoined(slackUser));
        }
Beispiel #20
0
        public async Task <SlackUser> GetSlackUserWithName(string token, string name, int searchLimit = 50)
        {
            var retryPolicy = Policy
                              .Handle <ApiException>(e =>
            {
                var slackFailedResponse = JsonConvert.DeserializeObject <SlackFailedResponse>(e.Content);

                return(slackFailedResponse.Error.Equals(ErrorTypes.RateLimited));
            })
                              .WaitAndRetryAsync(10, (retry) => TimeSpan.FromMilliseconds(retry * 200));

            var endSearch = false;

            SlackUser userWithName = null;

            var apiCursor = "";

            while (!endSearch && userWithName == null)
            {
                var policyResult = await retryPolicy.ExecuteAndCaptureAsync(async() =>
                {
                    var userResponse = await _slackApi.GetUsers(token, searchLimit, apiCursor);

                    if (userResponse.Ok)
                    {
                        userWithName = userResponse
                                       .Users
                                       .Where(u => u.Name.Equals(name))
                                       .FirstOrDefault();

                        apiCursor = userResponse
                                    .NextCursor
                                    .Cursor;

                        if (string.IsNullOrWhiteSpace(apiCursor))
                        {
                            // we've got to the end of the search results
                            endSearch = true;
                        }
                    }
                    else
                    {
                        // something when wrong when communicating with
                        // the slack, end early and return null
                        endSearch = true;
                    }
                });

                if (policyResult.Outcome.Equals(OutcomeType.Failure))
                {
                    // we failed all the retry attempts or something else
                    // went wrong throw the exception
                    throw policyResult.FinalException;
                }
            }

            return(userWithName);
        }
        public static void Guard(this SlackUser slackUser) {
            if (slackUser == null) {
                throw new ArgumentNullException(nameof(slackUser));
            }

            if (string.IsNullOrEmpty(slackUser.Id)) {
                throw new ArgumentException(nameof(slackUser));
            }
        }
Beispiel #22
0
        public async Task IsUserWhitelisted_NonWhitelistedUser_False()
        {
            var faceWhitelist      = Create();
            var nonWhitelistedUser = new SlackUser {
                Id = Path.GetRandomFileName()
            };

            Assert.False(await faceWhitelist.IsUserWhitelisted(nonWhitelistedUser));
        }
Beispiel #23
0
 public SlackPerson(SlackUser user)
 {
     Id      = user.Id;
     Name    = user.Name;
     Mention = user.FormattedUserId;
     // SlackConnector does not provide an easy way to determine whether
     // a user is active or not.  The SlackMessenger should handle this.
     IsAdmin = user.IsAdmin;
 }
 /// <summary>
 /// ユーザを削除する
 /// </summary>
 /// <param name="user">削除するユーザー</param>
 public void Delete(SlackUser user)
 {
     using (var context = new DatabaseContext())
     {
         context.SlackUser.Attach(user);
         context.SlackUser.Remove(user);
         context.SaveChanges();
     }
 }
 public void Save(SlackUser user)
 {
     using (var context = new DatabaseContext())
     {
         context.SlackUser.AddOrUpdate(user);
         context.SlackNotificationFilter.AddOrUpdate(user.Filter);
         context.SaveChanges();
     }
 }
Beispiel #26
0
        private async Task RaiseUserJoined(SlackUser user)
        {
            var e = OnUserJoined;

            if (e != null)
            {
                await e(user);
            }
        }
Beispiel #27
0
        public void VerifyProfile_HasNoId_Throws()
        {
            var user = new SlackUser();

            var exception = Record.Exception(() => slackProfileValidator.ValidateProfile(user));

            Assert.IsType <ArgumentException>(exception);
            Assert.Contains("Id cannot be empty.", exception.Message);
        }
Beispiel #28
0
        public async Task VerifyProfile_HasNoId_Throws()
        {
            var user = new SlackUser();

            // ReSharper disable once PossibleNullReferenceException
            var exception = await Record.ExceptionAsync(() => slackProfileValidator.ValidateProfile(user));

            Assert.IsType <ArgumentException>(exception);
        }
Beispiel #29
0
        public async Task IsUserWhitelisted_WhitelistedUser_True()
        {
            var faceWhitelist   = Create();
            var whitelistedUser = new SlackUser {
                Id = Path.GetRandomFileName()
            };
            await faceWhitelist.WhitelistUser(whitelistedUser);

            Assert.True(await faceWhitelist.IsUserWhitelisted(whitelistedUser));
        }
        public async Task GetGraphics(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                if (!Directory.Exists(_secrets.AvatarDir()))
                {
                    Directory.CreateDirectory(_secrets.AvatarDir());
                }
                var users = _pokerDB.User.OrderBy(u => u.ID).ToList();
                var size  = new MagickGeometry(32, 32);
                size.IgnoreAspectRatio = true;
                //did something change?
                int counter = 0;
                foreach (var user in users)
                {
                    counter++;
                    string uid = user.SlackID;
                    string uri = "https://slack.com/api/users.profile.get?token=" + _secrets.UserToken() + "&user="******".png"))
                        {
                            MagickImage i = new MagickImage(await client.GetStreamAsync(u.Profile.Image48));
                            i.Resize(size);
                            if (File.Exists(_secrets.AvatarDir() + user.SlackID + ".png"))
                            {
                                File.Delete(_secrets.AvatarDir() + user.SlackID + ".png");
                            }
                            Console.WriteLine(_secrets.AvatarDir() + user.SlackID + ".png");
                            i.Write(_secrets.AvatarDir() + user.SlackID + ".png");
                            user.AvatarHash = u.Profile.AvatarHash;
                        }
                        if (!u.Profile.DisplayName.Equals(user.SlackUserName))
                        {
                            user.SlackUserName = u.Profile.DisplayName;
                        }
                        user.AvatarIndex = counter;
                    }
                    catch (HttpRequestException e)
                    {
                        Console.WriteLine("\nException Caught!");
                        Console.WriteLine("Message :{0} ", e.Message);
                    }
                    _pokerRepo.SetAvatarPath(user.UserName, _secrets.AvatarDir() + user.SlackID + ".png");
                    await Task.Delay(20000, cancellationToken);
                }

                _pokerDB.SaveChanges();
            }
            await Task.Delay(9000000, cancellationToken); //very long time
        }