Esempio n. 1
0
        public void TestGetGroupIdByUrl()
        {
            string url     = @"http://vk.com/v7paca";
            string groupId = Inviter.GetGroupIdByUrl(url);

            Assert.AreEqual("6206", groupId);
        }
Esempio n. 2
0
 public Invite()
 {
     OnClientUpdated += (sender, e) =>
     {
         Inviter.SetClient(Client);
     };
 }
Esempio n. 3
0
        public void Constructor_Should_Assign_Properties_And_Read_Customers_From_IO()
        {
            IOMockReadFromFileSetup();

            var customerInviter = new Inviter(ioMock.Object, expectedFilepath, radiusMock.Object);

            Assert.Equal(customerInviter.GetCustomers(), inputCustomers);
        }
Esempio n. 4
0
        public DiscordInvite()
        {
            OnClientUpdated += (sender, e) =>
            {
                Inviter.SetClient(Client);

                Channel.SetClient(Client);
            };
        }
Esempio n. 5
0
        public void InviteCustomers_Should_Return_False_If_No_Customers_Within_Radius()
        {
            IOMockReadFromFileSetup();

            RadiusMockIsWithinRadiusSetup(false);

            var customerInviterWithFalseRadiusMock = new Inviter(ioMock.Object, expectedFilepath, radiusMock.Object);

            Assert.False(customerInviterWithFalseRadiusMock.InviteCustomers(outputFilepath));
        }
Esempio n. 6
0
        public void InviteCustomers_Should_Return_True_If_Customers_Within_Radius_And_Wrote_Output()
        {
            IOMockReadFromFileSetup();

            RadiusMockIsWithinRadiusSetup(true);
            IOMockCreateOutputFileSetup(true);

            var customerInviterWithFalseRadiusMock = new Inviter(ioMock.Object, expectedFilepath, radiusMock.Object);

            IOMockCreateOutputFileSetup(true);
            Assert.True(customerInviterWithFalseRadiusMock.InviteCustomers(outputFilepath));
        }
Esempio n. 7
0
        public DiscordInvite()
        {
            OnClientUpdated += (sender, e) =>
            {
                Inviter.SetClient(Client);

                if (Guild != null)
                {
                    Guild.SetClient(Client);
                }

                Channel.SetClient(Client);
            };
            JsonUpdated += (sender, json) => Channel.SetJson(json.Value <JObject>("channel"));
        }
Esempio n. 8
0
        public DiscordInvite()
        {
            OnClientUpdated += (sender, e) =>
            {
                Inviter.SetClient(Client);

                if (Guild != null)
                {
                    ((GuildChannel)Channel).GuildId = Guild.Id;
                    Guild.SetClient(Client);
                }

                Channel.SetClient(Client);
            };
        }
Esempio n. 9
0
        public void GetCustomersWithinRadius_Should_Filter_Out_Customers_Based_On_Result_Of_IsWithinRadius_Call()
        {
            IOMockReadFromFileSetup();

            RadiusMockIsWithinRadiusSetup(true);

            var customerInviterWithTrueRadiusMock = new Inviter(ioMock.Object, expectedFilepath, radiusMock.Object);

            // always return true so entire list should be returned
            Assert.Equal(customerInviterWithTrueRadiusMock.GetCustomersWithinRadius(), inputCustomers);

            RadiusMockIsWithinRadiusSetup(false);

            var customerInviterWithFalseRadiusMock = new Inviter(ioMock.Object, expectedFilepath, radiusMock.Object);

            // always return false so nothing should be returned
            Assert.Equal(customerInviterWithFalseRadiusMock.GetCustomersWithinRadius(), new List <Customer>());
        }
Esempio n. 10
0
        //internal static Inviter CurrentInviter;

#pragma warning disable 4014

        internal static void OnMessageReceived(object sender, object message)
        {
            MainWin.Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(async() =>
            {
                if (message is StoreAccountBalanceNotification)
                {
                    StoreAccountBalanceNotification newBalance = (StoreAccountBalanceNotification)message;
                    InfoLabel.Content            = "IP: " + newBalance.Ip + " ∙ RP: " + newBalance.Rp;
                    Client.LoginPacket.IpBalance = newBalance.Ip;
                    Client.LoginPacket.RpBalance = newBalance.Rp;
                }
                else if (message is GameNotification)
                {
                    GameNotification notification    = (GameNotification)message;
                    MessageOverlay messageOver       = new MessageOverlay();
                    messageOver.MessageTitle.Content = notification.Type;
                    switch (notification.Type)
                    {
                    case "PLAYER_BANNED_FROM_GAME":
                        messageOver.MessageTitle.Content = "Banned from custom game";
                        messageOver.MessageTextBox.Text  = "You have been banned from this custom game!";
                        break;

                    default:
                        messageOver.MessageTextBox.Text = notification.MessageCode + Environment.NewLine;
                        messageOver.MessageTextBox.Text = Convert.ToString(notification.MessageArgument);
                        break;
                    }
                    Client.OverlayContainer.Content    = messageOver.Content;
                    Client.OverlayContainer.Visibility = Visibility.Visible;
                    Client.ClearPage(typeof(CustomGameLobbyPage));
                    if (messageOver.MessageTitle.Content.ToString() != "PLAYER_QUIT")
                    {
                        Client.SwitchPage(new MainPage());
                    }
                }
                else if (message is PVPNetConnect.RiotObjects.Platform.Statistics.EndOfGameStats)
                {
                    PVPNetConnect.RiotObjects.Platform.Statistics.EndOfGameStats stats = message as PVPNetConnect.RiotObjects.Platform.Statistics.EndOfGameStats;
                    EndOfGamePage EndOfGame = new EndOfGamePage(stats);
                    Client.ClearPage(typeof(TeamQueuePage));
                    Client.OverlayContainer.Visibility = Visibility.Visible;
                    Client.OverlayContainer.Content    = EndOfGame.Content;
                }
                else if (message is StoreFulfillmentNotification)
                {
                    PlayerChampions = await PVPNet.GetAvailableChampions();
                }
                else if (message is Inviter)
                {
                    Inviter stats = message as Inviter;
                    //CurrentInviter = stats;
                }
                else if (message is InvitationRequest)
                {
                    InvitationRequest stats = message as InvitationRequest;
                    //TypedObject body = (TypedObject)to["body"];
                    if (stats.Inviter != null)
                    {
                        try
                        {
                            //Already existant popup. Do not create a new one
                            var x = Client.InviteData[stats.InvitationId];
                            if (x.Inviter != null)
                            {
                                return;
                            }
                        }
                        catch
                        {
                        }
                        MainWin.Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                        {
                            GameInvitePopup pop     = new GameInvitePopup(stats);
                            pop.HorizontalAlignment = HorizontalAlignment.Right;
                            pop.VerticalAlignment   = VerticalAlignment.Bottom;
                            pop.Height = 230;
                            Client.NotificationGrid.Children.Add(pop);
                        }));
                    }
                }
            }));
        }
Esempio n. 11
0
        public static bool InviteCustomer(IO handler, IRadius radius, Input input)
        {
            Inviter customerInviter = new Inviter(handler, input.InputFilePath, radius);

            return(customerInviter.InviteCustomers(input.OutputFilePath));
        }
Esempio n. 12
0
        public static async Task ClientOnGuildMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
        {
            //Проверка на бан
            var userBans      = BanSQL.GetForUser(e.Member.Id);
            var unexpiredBans = new List <BanSQL>();

            foreach (var ban in userBans)
            {
                if (ban.UnbanDateTime > DateTime.Now)
                {
                    unexpiredBans.Add(ban);
                }
            }
            if (unexpiredBans.Any())
            {
                var message = "**У вас есть неистёкшие блокировки на этом сервере:** \n";
                foreach (var ban in unexpiredBans)
                {
                    message +=
                        $"• **Причина:** {ban.Reason}. **Истекает через** {Utility.FormatTimespan(ban.UnbanDateTime - DateTime.Now)} | {ban.UnbanDateTime:dd.MM.yyyy HH:mm:ss}\n";
                }

                try
                {
                    await e.Member.SendMessageAsync(message);
                }
                catch (UnauthorizedException)
                {
                    // if bot is in user's blacklist
                }

                await e.Member.BanAsync();

                return;
            }

            //Проверка на mute
            var reports = ReportSQL.GetForUser(e.Member.Id).Where(x => x.ReportEnd > DateTime.Now);

            if (reports.Any())
            {
                var blocksMessage = "**У вас есть неистекшие блокировки на этом сервере!**\n";
                foreach (var report in reports)
                {
                    string blockType = report.ReportType switch
                    {
                        ReportType.Mute => "Мут",
                        ReportType.CodexPurge => "Блокировка принятия правил",
                        ReportType.FleetPurge => "Блокировка рейдов",
                        ReportType.VoiceMute => "Мут в голосовых каналах",
                        _ => ""
                    };
                    blocksMessage += $"• **{blockType}:** истекает через {Utility.FormatTimespan(report.ReportEnd - DateTime.Now)}\n";

                    if (report.ReportType == ReportType.Mute)
                    {
                        await e.Member.GrantRoleAsync(e.Guild.GetRole(Bot.BotSettings.MuteRole));
                    }
                    else if (report.ReportType == ReportType.VoiceMute)
                    {
                        await e.Member.GrantRoleAsync(e.Guild.GetRole(Bot.BotSettings.VoiceMuteRole));
                    }
                    else if (report.ReportType == ReportType.CodexPurge)
                    {
                        await e.Member.GrantRoleAsync(e.Guild.GetRole(Bot.BotSettings.PurgeCodexRole));
                    }
                }

                try
                {
                    await e.Member.SendMessageAsync(blocksMessage);
                }
                catch (UnauthorizedException)
                {
                }
            }

            //Выдача доступа к приватным кораблям
            try
            {
                var ships = PrivateShip.GetUserShip(e.Member.Id);
                foreach (var ship in ships)
                {
                    await e.Guild.GetChannel(ship.Channel).AddOverwriteAsync(e.Member, Permissions.UseVoice);
                }
            }
            catch (Exception ex)
            {
                client.Logger.LogWarning(BotLoggerEvents.Event, $"Ошибка при выдаче доступа к приватному кораблю. \n{ex.Message}\n{ex.StackTrace}");
            }

            var invites      = Invites.AsReadOnly().ToList();   //Сохраняем список старых инвайтов в локальную переменную
            var guildInvites = await e.Guild.GetInvitesAsync(); //Запрашиваем новый список инвайтов

            Invites = guildInvites.ToList();                    //Обновляю список инвайтов

            try
            {
                await e.Member.SendMessageAsync($"**Привет, {e.Member.Mention}!\n**" +
                                                "Мы рады что ты присоединился к нашему сообществу :wink:!\n\n" +
                                                "Прежде чем приступать к игре, прочитай и прими правила в канале <#435486626551037963>.\n" +
                                                "После принятия можешь ознакомиться с гайдом по боту в канале <#476430819011985418>.\n" +
                                                "Если у тебя есть какие-то вопросы, не стесняйся писать администрации через бота. (Команда `!support`).\n\n" +
                                                "**Удачной игры!**");
            }
            catch (UnauthorizedException)
            {
                //Пользователь заблокировал бота
            }

            // Выдача ролей, которые были у участника перед выходом.
            if (UsersLeftList.Users.ContainsKey(e.Member.Id))
            {
                foreach (var role in UsersLeftList.Users[e.Member.Id].Roles)
                {
                    try
                    {
                        await e.Member.GrantRoleAsync(e.Guild.GetRole(role));
                    }
                    catch (NotFoundException)
                    {
                    }
                }

                UsersLeftList.Users.Remove(e.Member.Id);
                UsersLeftList.SaveToXML(Bot.BotSettings.UsersLeftXML);
            }

            //Определение инвайта
            try
            {
                //Находит обновившийся инвайт по количеству приглашений
                //Вызывает NullReferenceException в случае если ссылка только для одного использования
                var updatedInvite = guildInvites.ToList().Find(g => invites.Find(i => i.Code == g.Code).Uses < g.Uses);

                //Если не удалось определить инвайт, значит его нет в новых так как к.во использований ограничено и он был удален
                if (updatedInvite == null)
                {
                    updatedInvite = invites.Where(p => guildInvites.All(p2 => p2.Code != p.Code))                    //Ищем удаленный инвайт
                                    .Where(x => (x.CreatedAt.AddSeconds(x.MaxAge) < DateTimeOffset.Now))             //Проверяем если он не истёк
                                    .FirstOrDefault();                                                               //С такими условиями будет только один такой инвайт
                }

                if (updatedInvite != null)
                {
                    await e.Guild.GetChannel(Bot.BotSettings.UserlogChannel)
                    .SendMessageAsync(
                        $"**Участник присоединился:** {e.Member.Username}#{e.Member.Discriminator} ({e.Member.Id}) используя " +
                        $"приглашение {updatedInvite.Code} от участника {updatedInvite.Inviter.Username}#{updatedInvite.Inviter.Discriminator}. ");

                    client.Logger.LogInformation(BotLoggerEvents.Event, $"Участник {e.Member.Username}#{e.Member.Discriminator} ({e.Member.Id}) присоединился к серверу. " +
                                                 $"Приглашение: {updatedInvite.Code} от участника {updatedInvite.Inviter.Username}#{updatedInvite.Inviter.Discriminator}.");

                    //Проверяем если пригласивший уже существует, если нет то создаем
                    if (!InviterList.Inviters.ContainsKey(updatedInvite.Inviter.Id))
                    {
                        Inviter.Create(updatedInvite.Inviter.Id, e.Member.IsBot);
                    }

                    //Проверяем если пользователь был ранее приглашен другими и обновляем активность, если нет то вносим в список
                    if (InviterList.Inviters.ToList().Exists(x => x.Value.Referrals.ContainsKey(e.Member.Id)))
                    {
                        InviterList.Inviters.ToList().Where(x => x.Value.Referrals.ContainsKey(e.Member.Id)).ToList()
                        .ForEach(x => x.Value.UpdateReferral(e.Member.Id, true));
                    }
                    else
                    {
                        InviterList.Inviters[updatedInvite.Inviter.Id].AddReferral(e.Member.Id);
                    }

                    InviterList.SaveToXML(Bot.BotSettings.InviterXML);
                    //Обновление статистики приглашений
                    await LeaderboardCommands.UpdateLeaderboard(e.Guild);
                }
                else
                {
                    var guildInvite = await e.Guild.GetVanityInviteAsync();

                    if (guildInvite.Uses > GuildInviteUsage)
                    {
                        GuildInviteUsage = guildInvite.Uses;
                        await e.Guild.GetChannel(Bot.BotSettings.UserlogChannel).SendMessageAsync(
                            $"**Участник присоединился:** {e.Member.Username}#{e.Member.Discriminator} ({e.Member.Id}). " +
                            $"Используя персональную ссылку **{guildInvite.Code}**.");

                        client.Logger.LogInformation(BotLoggerEvents.Event, $"Участник {e.Member.Username}#{e.Member.Discriminator} ({e.Member.Id}) присоединился к серверу. Используя персональную ссылку {guildInvite.Code}.");
                    }
                    else
                    {
                        await e.Guild.GetChannel(Bot.BotSettings.UserlogChannel)
                        .SendMessageAsync(
                            $"**Участник присоединился:** {e.Member.Username}#{e.Member.Discriminator} ({e.Member.Id}). " +
                            $"Приглашение не удалось определить.");

                        client.Logger.LogInformation(BotLoggerEvents.Event, $"Участник {e.Member.Username}#{e.Member.Discriminator} ({e.Member.Id}) присоединился к серверу. Приглашение не удалось определить.");
                    }
                }
            }
            catch (Exception ex)
            {
                await e.Guild.GetChannel(Bot.BotSettings.UserlogChannel)
                .SendMessageAsync(
                    $"**Участник присоединился:** {e.Member.Username}#{e.Member.Discriminator} ({e.Member.Id}). " +
                    $"При попытке отследить инвайт произошла ошибка.");

                client.Logger.LogInformation(BotLoggerEvents.Event, $"Участник {e.Member.Username}#{e.Member.Discriminator} ({e.Member.Id}) присоединился к серверу. Приглашение не удалось определить.",
                                             DateTime.Now);

                client.Logger.LogWarning(BotLoggerEvents.Event, "Не удалось определить приглашение.",
                                         DateTime.Now);

                var errChannel = e.Guild.GetChannel(Bot.BotSettings.ErrorLog);

                var message = "**Ошибка при логгинге инвайта**\n" +
                              $"**Пользователь:** {e.Member}\n" +
                              $"**Исключение:** {ex.GetType()}:{ex.Message}\n" +
                              $"**Трассировка стека:** \n```{ex.StackTrace}```\n" +
                              $"{ex}";

                await errChannel.SendMessageAsync(message);
            }

            //Обновляем статус бота
            await Bot.UpdateBotStatusAsync(client, e.Guild);
        }
Esempio n. 13
0
        //internal static Inviter CurrentInviter;

        internal static void OnMessageReceived(object sender, object message)
        {
            MainWin.Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(async() =>
            {
                if (message is StoreAccountBalanceNotification)
                {
                    StoreAccountBalanceNotification newBalance = (StoreAccountBalanceNotification)message;
                    InfoLabel.Content            = "IP: " + newBalance.Ip + " ∙ RP: " + newBalance.Rp;
                    Client.LoginPacket.IpBalance = newBalance.Ip;
                    Client.LoginPacket.RpBalance = newBalance.Rp;
                }
                else if (message is GameNotification)
                {
                    GameNotification notification    = (GameNotification)message;
                    MessageOverlay messageOver       = new MessageOverlay();
                    messageOver.MessageTitle.Content = notification.Type;
                    switch (notification.Type)
                    {
                    case "PLAYER_BANNED_FROM_GAME":
                        messageOver.MessageTitle.Content = "Banned from custom game";
                        messageOver.MessageTextBox.Text  = "You have been banned from this custom game!";
                        break;

                    default:
                        messageOver.MessageTextBox.Text = notification.MessageCode + Environment.NewLine;
                        messageOver.MessageTextBox.Text = Convert.ToString(notification.MessageArgument);
                        break;
                    }
                    Client.OverlayContainer.Content    = messageOver.Content;
                    Client.OverlayContainer.Visibility = Visibility.Visible;
                    Client.ClearPage(new CustomGameLobbyPage());
                    Client.SwitchPage(new MainPage());
                }
                else if (message is EndOfGameStats)
                {
                    EndOfGameStats stats               = message as EndOfGameStats;
                    EndOfGamePage EndOfGame            = new EndOfGamePage(stats);
                    Client.OverlayContainer.Visibility = Visibility.Visible;
                    Client.OverlayContainer.Content    = EndOfGame.Content;
                }
                else if (message is StoreFulfillmentNotification)
                {
                    PlayerChampions = await PVPNet.GetAvailableChampions();
                }
                else if (message is Inviter)
                {
                    Inviter stats = message as Inviter;
                    //CurrentInviter = stats;
                }
                else if (message is InvitationRequest)
                {
                    InvitationRequest stats = message as InvitationRequest;
                    Inviter Inviterstats    = message as Inviter;
                    //TypedObject body = (TypedObject)to["body"];
                    MainWin.Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                    {
                        //Gameinvite stuff
                        GameInvitePopup pop = new GameInvitePopup(stats);
                        //await Invite.Callback;
                        //Invite.InvitationRequest(body);
                        pop.HorizontalAlignment = HorizontalAlignment.Right;
                        pop.VerticalAlignment   = VerticalAlignment.Bottom;
                        pop.Height = 230;
                        Client.NotificationGrid.Children.Add(pop);
                        //Client.InviteJsonRequest = LegendaryClient.Logic.JSON.InvitationRequest.PopulateGameInviteJson();
                        //message.GetType() == typeof(GameInvitePopup)
                    }));
                }
            }));
        }