Example #1
0
    /// <summary>
    /// Executes the job
    /// </summary>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public override async Task ExecuteAsync()
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var serviceProvider = GlobalServiceProvider.Current.GetServiceProvider();
            await using (serviceProvider.ConfigureAwait(false))
            {
                var achievementService = serviceProvider.GetService <AchievementService>();

                await achievementService.ImportAchievements()
                .ConfigureAwait(false);

                foreach (var account in await dbFactory.GetRepository <GuildWarsAccountRepository>()
                         .GetQuery()
                         .Select(obj => new
                {
                    obj.Name,
                    obj.ApiKey
                })
                         .ToListAsync()
                         .ConfigureAwait(false))
                {
                    try
                    {
                        await achievementService.ImportAccountAchievements(account.Name, account.ApiKey)
                        .ConfigureAwait(false);
                    }
                    catch (MissingGuildWars2ApiPermissionException ex)
                    {
                        LoggingService.AddJobLogEntry(LogEntryLevel.Error, nameof(AchievementImportJob), $"Missing permissions {account}", null, ex);
                    }
                }
            }
        }
    }
Example #2
0
 /// <summary>
 /// Executes the job.
 /// </summary>
 public void Execute()
 {
     using (var dbFactory = RepositoryFactory.CreateInstance())
     {
         if (dbFactory.ExecuteSqlCommand($"BACKUP DATABASE [{Environment.GetEnvironmentVariable("SCRUFFY_DB_CATALOG")}] TO  DISK = N'{Environment.GetEnvironmentVariable("SCRUFFY_DB_BACKUP_DIRECTORY")}{Environment.GetEnvironmentVariable("SCRUFFY_DB_CATALOG")}_{DateTime.Now:yyyyMMdd}.bak' WITH NOFORMAT, NOINIT,  NAME = N'{Environment.GetEnvironmentVariable("SCRUFFY_DB_CATALOG")}-Full Database Backup', SKIP, NOREWIND, NOUNLOAD") == null)
         {
             LoggingService.AddJobLogEntry(LogEntryLevel.CriticalError, nameof(BackupJob), dbFactory.LastError.Message, null, dbFactory.LastError.ToString());
         }
     }
 }
Example #3
0
    /// <summary>
    /// Executes the job
    /// </summary>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public override async Task ExecuteAsync()
    {
        var date = DateTime.Today.AddDays(-1);

        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            foreach (var account in dbFactory.GetRepository <AccountRepository>()
                     .GetQuery()
                     .Select(obj => new
            {
                obj.Name,
                obj.ApiKey,
                obj.LastAge,
                WordId = obj.WorldId
            })
                     .ToList())
            {
                try
                {
                    var connector = new GuidWars2ApiConnector(account.ApiKey);
                    await using (connector.ConfigureAwait(false))
                    {
                        var accountInformation = await connector.GetAccountInformationAsync()
                                                 .ConfigureAwait(false);

                        if (accountInformation.Age != account.LastAge)
                        {
                            dbFactory.GetRepository <AccountDailyLoginCheckRepository>()
                            .Add(new GuildWarsAccountDailyLoginCheckEntity
                            {
                                Name = account.Name,
                                Date = date
                            });

                            dbFactory.GetRepository <AccountRepository>()
                            .Refresh(obj => obj.Name == account.Name,
                                     obj =>
                            {
                                obj.LastAge = accountInformation.Age;
                                obj.WorldId = accountInformation.World;
                                obj.DailyAchievementPoints   = accountInformation.DailyAchievementPoints;
                                obj.MonthlyAchievementPoints = accountInformation.MonthlyAchievementPoints;
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.AddJobLogEntry(LogEntryLevel.CriticalError, nameof(AccountLoginCheckJob), account.Name, ex.Message, ex.ToString());
                }
            }
        }
    }
Example #4
0
    /// <summary>
    /// Executes the job
    /// </summary>
    public void Execute()
    {
        try
        {
            LoggingService.AddJobLogEntry(LogEntryLevel.Information, GetType().Name, "Job started");

            Task.Run(ExecuteAsync).Wait();
        }
        catch (Exception ex)
        {
            LoggingService.AddJobLogEntry(LogEntryLevel.CriticalError, GetType().Name, ex.Message, null, ex);
        }
    }
Example #5
0
    /// <summary>
    /// Executes the job
    /// </summary>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public override async Task ExecuteAsync()
    {
        var serviceProvider = GlobalServiceProvider.Current.GetServiceProvider();

        await using (serviceProvider.ConfigureAwait(false))
        {
            var client = serviceProvider.GetService <DiscordClient>();
            var userManagementService = serviceProvider.GetService <UserManagementService>();

            using (var dbFactory = RepositoryFactory.CreateInstance())
            {
                foreach (var configuration in dbFactory.GetRepository <GuildSpecialRankConfigurationRepository>()
                         .GetQuery()
                         .Where(obj => obj.IsDeleted == false)
                         .Select(obj => new
                {
                    obj.Id,
                    obj.Guild.DiscordServerId,
                    obj.MaximumPoints,
                    Roles = obj.GuildSpecialRankRoleAssignments
                            .Select(obj2 => new
                    {
                        obj2.DiscordRoleId,
                        obj2.Points
                    }),
                    IgnoreRoles = obj.GuildSpecialRankIgnoreRoleAssignments
                                  .Select(obj2 => obj2.DiscordRoleId)
                })
                         .ToList())
                {
                    var points = new List <(ulong UserId, double Points)>();

                    var guild = await client.GetGuildAsync(configuration.DiscordServerId)
                                .ConfigureAwait(false);

                    foreach (var user in await guild.GetAllMembersAsync()
                             .ConfigureAwait(false))
                    {
                        if (configuration.IgnoreRoles.Any(obj => user.Roles.Any(obj2 => obj2.Id == obj)) == false)
                        {
                            foreach (var role in configuration.Roles)
                            {
                                if (user.Roles.Any(obj => obj.Id == role.DiscordRoleId))
                                {
                                    points.Add((user.Id, role.Points));
                                }
                            }
                        }
                    }

                    var discordUserAccountIds = points.Select(obj => obj.UserId)
                                                .ToList();

                    var users = dbFactory.GetRepository <DiscordAccountRepository>()
                                .GetQuery()
                                .Where(obj => discordUserAccountIds.Contains(obj.Id))
                                .ToDictionary(obj => obj.Id, obj => obj.UserId);

                    foreach (var pointsPerUser in points.GroupBy(obj => obj.UserId))
                    {
                        await userManagementService.CheckDiscordAccountAsync(pointsPerUser.Key)
                        .ConfigureAwait(false);

                        var transaction = dbFactory.BeginTransaction(IsolationLevel.RepeatableRead);
                        await using (transaction.ConfigureAwait(false))
                        {
                            if (users.TryGetValue(pointsPerUser.Key, out var userId))
                            {
                                if (await dbFactory.GetRepository <GuildSpecialRankPointsRepository>()
                                    .AddPoints(configuration.Id, configuration.MaximumPoints, userId, pointsPerUser.Select(obj => obj.Points).ToList())
                                    .ConfigureAwait(false))
                                {
                                    await transaction.CommitAsync()
                                    .ConfigureAwait(false);
                                }
                            }
                        }
                    }
                }

                var channels = dbFactory.GetRepository <GuildChannelConfigurationRepository>()
                               .GetQuery()
                               .Select(obj => obj);

                foreach (var configuration in dbFactory.GetRepository <GuildSpecialRankConfigurationRepository>()
                         .GetQuery()
                         .Where(obj => obj.IsDeleted == false)
                         .Select(obj => new
                {
                    obj.Id,
                    obj.Description,
                    obj.Guild.DiscordServerId,
                    obj.DiscordRoleId,
                    ChannelId = channels.Where(obj2 => obj2.GuildId == obj.GuildId &&
                                               obj2.Type == GuildChannelConfigurationType.SpecialRankRankChange)
                                .Select(obj2 => (ulong?)obj2.DiscordChannelId)
                                .FirstOrDefault(),
                    Users = obj.GuildSpecialRankPoints
                            .Where(obj2 => obj2.Points > obj.RemoveThreshold)
                            .SelectMany(obj2 => obj2.User
                                        .DiscordAccounts
                                        .Select(obj3 => new
                    {
                        obj3.Id,
                        IsGrantRole = obj2.Points > obj.GrantThreshold
                    })),
                    IgnoreRoles = obj.GuildSpecialRankIgnoreRoleAssignments
                                  .Select(obj2 => obj2.DiscordRoleId)
                })
                         .ToList())
                {
                    var actions = new List <(bool IsGrant, DiscordMember User, ulong RoleId)>();

                    var guild = await client.GetGuildAsync(configuration.DiscordServerId)
                                .ConfigureAwait(false);

                    foreach (var user in await guild.GetAllMembersAsync()
                             .ConfigureAwait(false))
                    {
                        if (configuration.IgnoreRoles.Any(obj => user.Roles.Any(obj2 => obj2.Id == obj)) == false)
                        {
                            var isRoleAssigned = user.Roles.Any(obj => obj.Id == configuration.DiscordRoleId);
                            if (isRoleAssigned)
                            {
                                if (configuration.Users.Any(obj => obj.Id == user.Id) == false)
                                {
                                    actions.Add((false, user, configuration.DiscordRoleId));
                                }
                            }
                            else if (configuration.Users.FirstOrDefault(obj => obj.Id == user.Id)?.IsGrantRole == true)
                            {
                                actions.Add((true, user, configuration.DiscordRoleId));
                            }
                        }
                    }

                    if (actions.Count > 0)
                    {
                        foreach (var action in actions)
                        {
                            try
                            {
                                var role = action.User.Guild.GetRole(action.RoleId);
                                if (role != null)
                                {
                                    if (action.IsGrant)
                                    {
                                        await action.User
                                        .GrantRoleAsync(role)
                                        .ConfigureAwait(false);

                                        LoggingService.AddJobLogEntry(LogEntryLevel.Warning, nameof(GuildSpecialRankPointsJob), $"Role granted: configuration {configuration.Id}; user: {action.User.Id}; role: {role.Id}");
                                    }
                                    else
                                    {
                                        await action.User
                                        .RevokeRoleAsync(role)
                                        .ConfigureAwait(false);

                                        LoggingService.AddJobLogEntry(LogEntryLevel.Warning, nameof(GuildSpecialRankPointsJob), $"Role revoked: configuration {configuration.Id}; user: {action.User.Id}; role: {role.Id}");
                                    }
                                }
                                else
                                {
                                    LoggingService.AddJobLogEntry(LogEntryLevel.Error, nameof(GuildSpecialRankPointsJob), "Role assignment", $"Unknown role {action.RoleId} at {action.User.Guild.Id}", null);
                                }
                            }
                            catch (Exception ex)
                            {
                                LoggingService.AddJobLogEntry(LogEntryLevel.Error, nameof(GuildSpecialRankPointsJob), "Role assignment", null, ex);
                            }
                        }

                        if (configuration.ChannelId != null)
                        {
                            var builder = new DiscordEmbedBuilder();
                            builder.WithTitle(LocalizationGroup.GetText("RoleAssignment", "Role assignment"));
                            builder.WithDescription($"{configuration.Description} ({guild.GetRole(configuration.DiscordRoleId).Mention})");
                            builder.WithColor(DiscordColor.DarkBlue);

                            if (actions.Any(obj => obj.IsGrant == false))
                            {
                                var stringBuilder = new StringBuilder();

                                foreach (var action in actions.Where(obj => obj.IsGrant == false))
                                {
                                    stringBuilder.AppendLine(DiscordEmojiService.GetBulletEmoji(client) + " " + action.User.Mention);
                                }

                                builder.AddField(LocalizationGroup.GetText("RemovedRoles", "Removed roles"), stringBuilder.ToString());
                            }

                            if (actions.Any(obj => obj.IsGrant))
                            {
                                var stringBuilder = new StringBuilder();

                                foreach (var action in actions.Where(obj => obj.IsGrant))
                                {
                                    stringBuilder.AppendLine(DiscordEmojiService.GetBulletEmoji(client) + " " + action.User.Mention);
                                }

                                builder.AddField(LocalizationGroup.GetText("GrantedRoles", "Granted roles"), stringBuilder.ToString());
                            }

                            var channel = await client.GetChannelAsync(configuration.ChannelId.Value)
                                          .ConfigureAwait(false);

                            await channel.SendMessageAsync(builder)
                            .ConfigureAwait(false);
                        }
                        else
                        {
                            LoggingService.AddJobLogEntry(LogEntryLevel.Warning, nameof(GuildSpecialRankPointsJob), $"No notification channel for configuration {configuration.Id}");
                        }
                    }
                }
            }
        }
    }
Example #6
0
    /// <summary>
    /// Executes the job
    /// </summary>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public override async Task ExecuteAsync()
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var serviceProvider = GlobalServiceProvider.Current.GetServiceProvider();
            await using (serviceProvider.ConfigureAwait(false))
            {
                var discordClient    = serviceProvider.GetService <DiscordClient>();
                var guildRankService = new Lazy <GuildRankService>(() => serviceProvider.GetService <GuildRankService>());

                var channels = dbFactory.GetRepository <GuildChannelConfigurationRepository>()
                               .GetQuery()
                               .Select(obj => obj);

                foreach (var guild in dbFactory.GetRepository <GuildRepository>()
                         .GetQuery()
                         .Select(obj => new
                {
                    obj.Id,
                    obj.ApiKey,
                    obj.GuildId,
                    LastLogEntryId = obj.GuildLogEntries
                                     .Select(obj2 => obj2.Id)
                                     .OrderByDescending(obj2 => obj2)
                                     .FirstOrDefault(),
                    ChannelId = channels.Where(obj2 => obj2.GuildId == obj.Id &&
                                               obj2.Type == GuildChannelConfigurationType.GuildLogNotification)
                                .Select(obj2 => (ulong?)obj2.DiscordChannelId)
                                .FirstOrDefault()
                })
                         .ToList())
                {
                    var discordChannel = guild.ChannelId != null
                                             ? await discordClient.GetChannelAsync(guild.ChannelId.Value)
                                         .ConfigureAwait(false)
                                             : null;

                    var connector = new GuidWars2ApiConnector(guild.ApiKey);
                    await using (connector.ConfigureAwait(false))
                    {
                        try
                        {
                            foreach (var entry in (await connector.GetGuildLogEntries(guild.GuildId, guild.LastLogEntryId).ConfigureAwait(false)).OrderBy(obj => obj.Id))
                            {
                                if (dbFactory.GetRepository <GuildLogEntryRepository>()
                                    .Add(new GuildLogEntryEntity
                                {
                                    GuildId = guild.Id,
                                    Id = entry.Id,
                                    Time = entry.Time.ToLocalTime(),
                                    Type = entry.Type,
                                    User = entry.User,
                                    KickedBy = entry.KickedBy,
                                    InvitedBy = entry.InvitedBy,
                                    Operation = entry.Operation,
                                    ItemId = entry.ItemId,
                                    Count = entry.Count,
                                    Coins = entry.Coins,
                                    ChangedBy = entry.ChangedBy,
                                    OldRank = entry.OldRank,
                                    NewRank = entry.NewRank,
                                    UpgradeId = entry.UpgradeId,
                                    RecipeId = entry.RecipeId,
                                    Action = entry.Action,
                                    Activity = entry.Activity,
                                    TotalParticipants = entry.TotalParticipants,
                                    Participants = string.Join(';', entry.Participants?.Where(obj => string.IsNullOrWhiteSpace(obj) == false) ?? Array.Empty <string>()),
                                    MessageOfTheDay = entry.MessageOfTheDay
                                }))
                                {
                                    switch (entry.Type)
                                    {
                                    case GuildLogEntryEntity.Types.Joined:
                                    {
                                        await OnJoined(discordChannel, entry).ConfigureAwait(false);
                                    }
                                    break;

                                    case GuildLogEntryEntity.Types.Kick:
                                    {
                                        await OnKick(discordChannel, entry).ConfigureAwait(false);
                                    }
                                    break;

                                    case GuildLogEntryEntity.Types.RankChange:
                                    {
                                        await OnRankChanged(guildRankService.Value, guild.Id, entry).ConfigureAwait(false);
                                    }
                                    break;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LoggingService.AddJobLogEntry(LogEntryLevel.Warning, nameof(GuildLogImportJob), ex.Message, null, ex);
                        }
                    }
                }
            }
        }
    }