Пример #1
0
        /// <summary>
        /// Sets the ass font.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param>
        /// <returns>Task.</returns>
        private async Task SetAssFont(string file, CancellationToken cancellationToken = default)
        {
            _logger.LogInformation("Setting ass font within {File}", file);

            string   text;
            Encoding encoding;

            using (var fileStream = AsyncFile.OpenRead(file))
                using (var reader = new StreamReader(fileStream, true))
                {
                    encoding = reader.CurrentEncoding;

                    text = await reader.ReadToEndAsync().ConfigureAwait(false);
                }

            var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal);

            if (!string.Equals(text, newText, StringComparison.Ordinal))
            {
                var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
                var writer     = new StreamWriter(fileStream, encoding);
                await using (fileStream.ConfigureAwait(false))
                    await using (writer.ConfigureAwait(false))
                    {
                        await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false);
                    }
            }
        }
Пример #2
0
    /// <summary>
    /// Exporting login data
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task ExportLoginActivityLog(CommandContextContainer commandContext)
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var dateLimit = DateTime.Today.AddDays(-7);

            var entries = await dbFactory.GetRepository <AccountDailyLoginCheckRepository>()
                          .GetQuery()
                          .Where(obj => obj.Date >= dateLimit)
                          .Select(obj => new
            {
                obj.Account.Name
            })
                          .Distinct()
                          .ToListAsync()
                          .ConfigureAwait(false);

            var memoryStream = new MemoryStream();
            await using (memoryStream.ConfigureAwait(false))
            {
                var writer = new StreamWriter(memoryStream);
                await using (writer.ConfigureAwait(false))
                {
                    await writer.WriteLineAsync("AccountName")
                    .ConfigureAwait(false);

                    foreach (var entry in entries)
                    {
                        await writer.WriteLineAsync($"{entry.Name};")
                        .ConfigureAwait(false);
                    }

                    await writer.FlushAsync()
                    .ConfigureAwait(false);

                    memoryStream.Position = 0;

                    await commandContext.Channel
                    .SendMessageAsync(new DiscordMessageBuilder().WithFile("activity_log.csv", memoryStream))
                    .ConfigureAwait(false);
                }
            }
        }
    }
Пример #3
0
        private static async ValueTask SaveZoneIdentifier(string filename, IPAddress?ipa)
        {
            var fs = new FileStream(filename + ":Zone.Identifier", FileMode.Create, FileAccess.Write, FileShare.None);

            await using (fs.ConfigureAwait(false)) {
                var sw = new StreamWriter(fs);
                await using (sw.ConfigureAwait(false)) {
                    await sw.WriteLineAsync("[ZoneTransfer]");

                    await sw.WriteLineAsync("ZoneId=3");

                    if (ipa is not null)
                    {
                        await sw.WriteLineAsync($"HostIpAddress={ipa}");
                    }
                    await sw.WriteLineAsync("CocoaLogViewer=FormReceiver");
                }
            }
        }
Пример #4
0
        public async Task <ActionResult> DumpProfiles([FromServices] RurikawaDb db)
        {
            var ptr = db.Profiles.AsAsyncEnumerable();

            Response.ContentType = "application/csv";
            Response.StatusCode  = 200;
            await Response.StartAsync();

            int flushInterval = 50;

            await Task.Run(async() => {
                // write to body of response
                using var sw             = new StreamWriter(new StreamAsyncAdaptor(Response.Body));
                await using var swGuard  = sw.ConfigureAwait(false);
                var csvWriter            = new CsvWriter(sw);
                csvWriter.QuoteAllFields = true;

                csvWriter.WriteField("username");
                csvWriter.WriteField("studentId");
                csvWriter.WriteField("email");

                csvWriter.NextRecord();

                int counter = 0;
                await foreach (var val in ptr)
                {
                    if (counter % flushInterval == 0)
                    {
                        await sw.FlushAsync();
                    }

                    csvWriter.WriteField(val.Username);
                    csvWriter.WriteField(val.StudentId);
                    csvWriter.WriteField(val.Email);
                    csvWriter.NextRecord();

                    counter++;
                }
                await sw.FlushAsync();
            });

            return(new EmptyResult());
        }
Пример #5
0
    /// <summary>
    /// Exporting guild roles
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task ExportGuildRoles(CommandContextContainer commandContext)
    {
        var members = new List <(string Role, string User)>();

        foreach (var user in await commandContext.Guild
                 .GetAllMembersAsync()
                 .ConfigureAwait(false))
        {
            foreach (var role in user.Roles)
            {
                members.Add((role.Name, user.TryGetDisplayName()));
            }
        }

        var memoryStream = new MemoryStream();

        await using (memoryStream.ConfigureAwait(false))
        {
            var writer = new StreamWriter(memoryStream);

            await using (writer.ConfigureAwait(false))
            {
                await writer.WriteLineAsync("Role;User")
                .ConfigureAwait(false);

                foreach (var(role, user) in members.OrderBy(obj => obj.Role)
                         .ThenBy(obj => obj.User))
                {
                    await writer.WriteLineAsync($"{role};{user}")
                    .ConfigureAwait(false);
                }

                await writer.FlushAsync()
                .ConfigureAwait(false);

                memoryStream.Position = 0;

                await commandContext.Channel
                .SendMessageAsync(new DiscordMessageBuilder().WithFile("roles.csv", memoryStream))
                .ConfigureAwait(false);
            }
        }
    }
        /// <inheritdoc />
        internal override async Task <int> Transform(Stream input, Stream output, CancellationToken cancellationToken)
        {
            string json;

            using (var ms = new MemoryStream())
            {
                await input.CopyToAsync(ms, 1024, cancellationToken).ConfigureAwait(false);

                json = MessagePackSerializer.ConvertToJson(ms.ToArray());
            }

            var writer = new StreamWriter(output, Encodings.Utf8NoBom, 512, true);

            await using (writer.ConfigureAwait(false))
            {
                await writer.WriteAsync(json).ConfigureAwait(false);
            }

            return(ExitCodes.Ok);
        }
Пример #7
0
        public async Task <ActionResult> DumpSuiteAllJobs(
            [FromRoute] FlowSnake suiteId,
            [FromServices] RurikawaDb db)
        {
            var suite = await dbService.GetTestSuite(suiteId);

            if (suite == null)
            {
                return(NotFound());
            }

            var columns = suite.TestGroups
                          .SelectMany(group => group.Value.Select(value => value.Name))
                          .ToList();

            Response.ContentType = "application/csv";
            Response.StatusCode  = 200;
            Response.Headers.Add("Content-Disposition", $"inline; filename=\"{suiteId}.all-jobs.csv\"");

            await Response.StartAsync();

            // write to body of response
            using var sw            = new StreamWriter(new StreamAsyncAdaptor(Response.Body));
            await using var swGuard = sw.ConfigureAwait(false);
            var csvWriter = new CsvWriter(sw);


            const int batchSize = 100;
            var       startId   = FlowSnake.MaxValue;

            await WriteJobHeaders(csvWriter, columns);

            while (true)
            {
                var batch = db.Jobs
                            .OrderByDescending(job => job.Id)
                            .Where((job) => job.TestSuite == suiteId && job.Id < startId)
                            .Take(batchSize)
                            .Join(
                    db.Profiles,
                    (job) => job.Account,
                    (profile) => profile.Username,
                    (job, profile) =>
                    new JobDumpEntry {
                    Job = job, StudentId = profile.StudentId
                })
                            .ToList();

                if (batch.Count == 0)
                {
                    break;
                }
                startId = batch.Last().Job.Id;

                await Task.Run(() => {
                    foreach (var val in batch)
                    {
                        WriteJobInfo(csvWriter, val, columns);
                    }
                });

                await sw.FlushAsync();
            }


            return(new EmptyResult());
        }
Пример #8
0
    /// <summary>
    /// Exporting guild members
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task ExportGuildMembers(CommandContextContainer commandContext)
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var guild = dbFactory.GetRepository <GuildRepository>()
                        .GetQuery()
                        .Where(obj => obj.DiscordServerId == commandContext.Guild.Id)
                        .Select(obj => new
            {
                obj.GuildId,
                obj.ApiKey
            })
                        .FirstOrDefault();

            var accounts = await dbFactory.GetRepository <AccountRepository>()
                           .GetQuery()
                           .Select(obj => new
            {
                Name       = obj.Name.ToLower(),
                Permission = obj.Permissions
            })
                           .ToListAsync()
                           .ConfigureAwait(false);

            var members = new List <(string Name, DateTime?Joined, bool IsApiKeyValid, bool HasAllPermissions)>();

            var connector = new GuidWars2ApiConnector(guild.ApiKey);
            await using (connector.ConfigureAwait(false))
            {
                foreach (var member in await connector.GetGuildMembers(guild.GuildId)
                         .ConfigureAwait(false))
                {
                    var account = accounts.FirstOrDefault(obj => obj.Name == member.Name.ToLower());

                    members.Add((member.Name,
                                 member.Joined,
                                 account != null,
                                 account?.Permission.HasFlag(GuildWars2ApiPermission.RequiredPermissions) == true));
                }
            }

            var memoryStream = new MemoryStream();
            await using (memoryStream.ConfigureAwait(false))
            {
                var writer = new StreamWriter(memoryStream);
                await using (writer.ConfigureAwait(false))
                {
                    await writer.WriteLineAsync("AccountName;Joined;API-Key;Permissions")
                    .ConfigureAwait(false);

                    foreach (var(name, joined, isApiKeyValid, hasAllPermissions) in members.OrderBy(obj => obj.IsApiKeyValid).ThenBy(obj => obj.Name))
                    {
                        await writer.WriteLineAsync($"{name};{joined?.ToString("g", LocalizationGroup.CultureInfo)};{(isApiKeyValid ? "✔️" : "❌")};{(hasAllPermissions ? "✔️" : "❌")}")
                        .ConfigureAwait(false);
                    }

                    await writer.FlushAsync()
                    .ConfigureAwait(false);

                    memoryStream.Position = 0;

                    await commandContext.Channel
                    .SendMessageAsync(new DiscordMessageBuilder().WithFile("members.csv", memoryStream))
                    .ConfigureAwait(false);
                }
            }
        }
    }
Пример #9
0
    /// <summary>
    /// Exporting representation state
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task ExportRepresentation(CommandContextContainer commandContext)
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var guildId = dbFactory.GetRepository <GuildRepository>()
                          .GetQuery()
                          .Where(obj => obj.DiscordServerId == commandContext.Guild.Id)
                          .Select(obj => obj.GuildId)
                          .FirstOrDefault();

            var entries = await dbFactory.GetRepository <AccountRepository>()
                          .GetQuery()
                          .Select(obj => new
            {
                obj.Name,
                DiscordAccountId = obj.User
                                   .DiscordAccounts
                                   .Select(obj2 => obj2.Id)
                                   .FirstOrDefault(),
                obj.ApiKey
            })
                          .ToListAsync()
                          .ConfigureAwait(false);

            var accounts = new List <(string User, string AccountName, int Characters, int?Representation)>();

            foreach (var entry in entries)
            {
                DiscordMember user = null;

                try
                {
                    user = await commandContext.Guild
                           .GetMemberAsync(entry.DiscordAccountId)
                           .ConfigureAwait(false);
                }
                catch
                {
                }

                if (user != null)
                {
                    var connector = new GuidWars2ApiConnector(entry.ApiKey);
                    await using (connector.ConfigureAwait(false))
                    {
                        var characters = await connector.GetCharactersAsync()
                                         .ConfigureAwait(false);

                        accounts.Add((user.TryGetDisplayName(), entry.Name, characters?.Count ?? 0, characters?.Count(obj => obj.Guild == guildId) ?? 0));
                    }
                }
            }

            var memoryStream = new MemoryStream();
            await using (memoryStream.ConfigureAwait(false))
            {
                var writer = new StreamWriter(memoryStream);
                await using (writer.ConfigureAwait(false))
                {
                    await writer.WriteLineAsync("User;AccountName;Characters;Representation;Percentage")
                    .ConfigureAwait(false);

                    foreach (var(user, accountName, characters, representation) in accounts.OrderBy(obj => obj.User)
                             .ThenBy(obj => obj.AccountName))
                    {
                        await writer.WriteLineAsync($"{user};{accountName};{characters};{representation};{(characters != 0 ? representation / (double)characters : 0)}")
                        .ConfigureAwait(false);
                    }

                    await writer.FlushAsync()
                    .ConfigureAwait(false);

                    memoryStream.Position = 0;

                    await commandContext.Channel
                    .SendMessageAsync(new DiscordMessageBuilder().WithFile("representation.csv", memoryStream))
                    .ConfigureAwait(false);
                }
            }
        }
    }
Пример #10
0
    /// <summary>
    /// Exporting stash data
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <param name="sinceDate">Since date</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task ExportStashLog(CommandContextContainer commandContext, DateTime sinceDate)
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var logEntries = await dbFactory.GetRepository <GuildLogEntryRepository>()
                             .GetQuery()
                             .Where(obj => obj.Time > sinceDate &&
                                    obj.Type == "stash" &&
                                    obj.Guild.DiscordServerId == commandContext.Guild.Id)
                             .OrderBy(obj => obj.Time)
                             .Select(obj => new
            {
                obj.Id,
                obj.Time,
                obj.User,
                obj.Operation,
                obj.ItemId,
                obj.Count,
                obj.Coins
            })
                             .ToListAsync()
                             .ConfigureAwait(false);

            var itemIds = logEntries.Where(obj => obj.ItemId != null)
                          .Select(obj => obj.ItemId)
                          .Distinct()
                          .ToList();

            var connector = new GuidWars2ApiConnector(null);
            await using (connector.ConfigureAwait(false))
            {
                var tradingsPostValues = await connector.GetTradingPostPrices(itemIds)
                                         .ConfigureAwait(false);

                var items = await connector.GetItems(itemIds)
                            .ConfigureAwait(false);

                var memoryStream = new MemoryStream();
                await using (memoryStream.ConfigureAwait(false))
                {
                    var writer = new StreamWriter(memoryStream);
                    await using (writer.ConfigureAwait(false))
                    {
                        await writer.WriteLineAsync("TimeStamp;User;Operation;ItemId;ItemName;Count;TradingPostValue;VendorValue")
                        .ConfigureAwait(false);

                        foreach (var entry in logEntries)
                        {
                            var item             = items.FirstOrDefault(obj => obj.Id == entry.ItemId);
                            var tradingPostPrice = tradingsPostValues.FirstOrDefault(obj => obj.Id == entry.ItemId);

                            await writer.WriteLineAsync($"{entry.Time.ToString("g", LocalizationGroup.CultureInfo)};{entry.User};{entry.Operation};{entry.ItemId};{(entry.ItemId == null || entry.ItemId == 0 ? "Coins" : item?.Name)};{entry.Count};{tradingPostPrice?.TradingPostSellValue?.UnitPrice};{(entry.ItemId == null || entry.ItemId == 0 ? entry.Coins : item?.VendorValue)}")
                            .ConfigureAwait(false);
                        }

                        await writer.FlushAsync()
                        .ConfigureAwait(false);

                        memoryStream.Position = 0;

                        await commandContext.Channel
                        .SendMessageAsync(new DiscordMessageBuilder().WithFile("stash_log.csv", memoryStream))
                        .ConfigureAwait(false);
                    }
                }
            }
        }
    }
Пример #11
0
    /// <summary>
    /// Exporting stash data
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <param name="sinceDate">Since date</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task ExportUpgradesLogSummarized(CommandContextContainer commandContext, DateTime sinceDate)
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var logEntriesQuery = dbFactory.GetRepository <GuildLogEntryRepository>()
                                  .GetQuery()
                                  .Select(obj => obj);

            var logEntries = await dbFactory.GetRepository <GuildLogEntryRepository>()
                             .GetQuery()
                             .Where(obj => obj.Time > sinceDate &&
                                    obj.User != null &&
                                    obj.Type == "upgrade" &&
                                    (obj.Action == "completed"

                                     // Cause of some items, who don't generate 'completed' we have to check also the 'queued' entries.
                                     || (obj.Action == "queued" &&
                                         logEntriesQuery.Any(obj2 => obj2.Type == "upgrade" &&
                                                             obj2.UpgradeId == obj.UpgradeId &&
                                                             obj2.Action == "completed") == false)) &&
                                    obj.Guild.DiscordServerId == commandContext.Guild.Id)
                             .GroupBy(obj => new
            {
                obj.User,
                obj.ItemId,
                obj.UpgradeId
            })
                             .Select(obj => new
            {
                obj.Key.User,
                obj.Key.ItemId,
                obj.Key.UpgradeId,
                Count = obj.Sum(obj2 => obj2.Count ?? 1)
            })
                             .OrderBy(obj => obj.User)
                             .ThenBy(obj => obj.ItemId)
                             .ThenBy(obj => obj.UpgradeId)
                             .ToListAsync()
                             .ConfigureAwait(false);

            var itemIds = logEntries.Where(obj => obj.ItemId != null)
                          .Select(obj => obj.ItemId)
                          .Distinct()
                          .ToList();

            var upgradeIds = logEntries.Where(obj => obj.ItemId == null &&
                                              obj.UpgradeId != null)
                             .Select(obj => obj.UpgradeId)
                             .Distinct()
                             .ToList();

            var connector = new GuidWars2ApiConnector(null);
            await using (connector.ConfigureAwait(false))
            {
                var tradingsPostValues = await connector.GetTradingPostPrices(itemIds)
                                         .ConfigureAwait(false);

                var items = await connector.GetItems(itemIds)
                            .ConfigureAwait(false);

                var upgrades = await connector.GetUpgrades(upgradeIds)
                               .ConfigureAwait(false);

                var memoryStream = new MemoryStream();
                await using (memoryStream.ConfigureAwait(false))
                {
                    var writer = new StreamWriter(memoryStream);
                    await using (writer.ConfigureAwait(false))
                    {
                        await writer.WriteLineAsync("User;ItemId;ItemName;Count;TradingPostValue;VendorValue")
                        .ConfigureAwait(false);

                        foreach (var entry in logEntries)
                        {
                            var item             = items.FirstOrDefault(obj => obj.Id == entry.ItemId);
                            var tradingPostPrice = tradingsPostValues.FirstOrDefault(obj => obj.Id == entry.ItemId);

                            var itemName = entry.ItemId == null?
                                           upgrades.FirstOrDefault(obj => obj.Id == entry.UpgradeId)?.Name
                                           : item?.Name;

                            await writer.WriteLineAsync($"{entry.User};{entry.ItemId};{itemName};{entry.Count};{tradingPostPrice?.TradingPostSellValue?.UnitPrice};{item?.VendorValue}")
                            .ConfigureAwait(false);
                        }

                        await writer.FlushAsync()
                        .ConfigureAwait(false);

                        memoryStream.Position = 0;

                        await commandContext.Channel
                        .SendMessageAsync(new DiscordMessageBuilder().WithFile("upgrades_log.csv", memoryStream))
                        .ConfigureAwait(false);
                    }
                }
            }
        }
    }