private async Task <string> BuildTitleAsync(ISpecies species)
        {
            if (species is null)
            {
                throw new ArgumentNullException(nameof(species));
            }

            // Pages are created based on the first/primary common name (where available).
            // The full species name is added as a redirect.

            string title = string.Empty;

            if (!string.IsNullOrWhiteSpace(species.GetCommonName()))
            {
                title = species.GetCommonName();
            }
            else
            {
                IEnumerable <string> commonNames = species.CommonNames;

                if (commonNames.Count() > 0)
                {
                    title = commonNames.First();
                }
                else
                {
                    title = species.GetFullName();
                }
            }

            // If the title is empty for whatever reason (common names set to whitespace, for example), use the species' binomial name.

            if (string.IsNullOrWhiteSpace(title))
            {
                title = species.GetFullName();
            }

            // Trim any surrounding whitespace from the title.

            if (!string.IsNullOrEmpty(title))
            {
                title = title.Trim();
            }

            return(title);
        }
        private bool StringMatchesSpeciesName(string name, ISpecies species)
        {
            name = name.ToLower();

            return(name == species.Name.ToLower() ||
                   name == species.GetShortName().ToLower() ||
                   name == species.GetFullName().ToLower() ||
                   (!string.IsNullOrEmpty(species.GetCommonName()) && name == species.GetCommonName().ToLower()));
        }
Exemple #3
0
        private static string GeneratePictureFilenameFromSpecies(ISpecies species)
        {
            if (string.IsNullOrEmpty(species.GetPictureUrl()))
            {
                return(string.Empty);
            }

            string pictureFilename = GetPictureFilenameFromPictureUrl(species.GetPictureUrl());

            return(string.Format("{0}{1}", species.GetFullName().ToLower().Replace(' ', '_'), System.IO.Path.GetExtension(pictureFilename).ToLower()));
        }
        public static string GetWikiPageTitle(ISpecies species)
        {
            // This is the same process as used in SpeciesPageBuilder.BuildTitleAsync.
            // #todo Instead of being copy-pasted, this process should be in its own function used by both classes.

            string title;

            if (!string.IsNullOrWhiteSpace(species.GetCommonName()))
            {
                title = species.GetCommonName();
            }
            else
            {
                title = species.GetFullName();
            }

            title = title.SafeTrim();

            return(title);
        }
        private async Task ReplyAppendDescriptionAsync(ISpecies species)
        {
            if (species.IsValid())
            {
                IMessage message = new Message($"Reply with the description for {species.GetRank().GetName()} **{species.GetFullName()}**.");
                IResponsiveMessageResponse response = await ResponsiveMessageService.GetResponseAsync(Context, message);

                if (!response.Canceled)
                {
                    await ReplyAppendDescriptionAsync(species, await GetDescriptionFromMessageAsync(response.Message));
                }
            }
        }
        public async Task <IPaginatedMessage> BuildSpeciesMessageAsync(ISpecies species)
        {
            if (!species.IsValid())
            {
                return(null);
            }

            Discord.Messaging.Embed embed = new Discord.Messaging.Embed {
                Title = species.GetFullName()
            };

            if (species.CommonNames.Count() > 0)
            {
                embed.Title += string.Format(" ({0})", string.Join(", ", species.CommonNames.Select(name => name.ToTitle())));
            }

            if (Config.GenerationsEnabled)
            {
                // Add a field for the generation.

                IGeneration gen = await Db.GetGenerationByDateAsync(species.CreationDate);

                embed.AddField("Gen", gen is null ? "???" : gen.Number.ToString(), inline: true);
            }

            // Add a field for the species owner.

            embed.AddField("Owner", await GetCreatorAsync(species.Creator), inline: true);

            // Add a field for the species' zones.

            IEnumerable <ISpeciesZoneInfo> speciesZoneList = (await Db.GetZonesAsync(species))
                                                             .Where(info => !info.Zone.Flags.HasFlag(ZoneFlags.Retired));

            string zonesFieldValue = speciesZoneList.ToString(ZoneListToStringOptions.Default, DiscordUtilities.MaxFieldLength);

            embed.AddField("Zone(s)", string.IsNullOrEmpty(zonesFieldValue) ? "None" : zonesFieldValue, inline: true);

            // Add the species' description.

            StringBuilder descriptionBuilder = new StringBuilder();

            if (species.IsExtinct())
            {
                embed.Title = "[EXTINCT] " + embed.Title;

                if (!string.IsNullOrEmpty(species.Status.Reason))
                {
                    descriptionBuilder.AppendLine(string.Format("**Extinct ({0}):** _{1}_\n", await BotUtils.TimestampToDateStringAsync(DateUtilities.GetTimestampFromDate((DateTimeOffset)species.Status.Date), BotContext), species.Status.Reason));
                }
            }

            descriptionBuilder.Append(species.GetDescriptionOrDefault());

            embed.Description = descriptionBuilder.ToString();

            // Add the species' picture.

            embed.ThumbnailUrl = species.GetPictureUrl();

            if (!string.IsNullOrEmpty(Config.WikiUrlFormat))
            {
                // Discord automatically encodes certain characters in URIs, which doesn't allow us to update the config via Discord when we have "{0}" in the URL.
                // Replace this with the proper string before attempting to call string.Format.

                string format = Config.WikiUrlFormat.Replace("%7B0%7D", "{0}");

                embed.Url = string.Format(format, Uri.EscapeUriString(WikiUtilities.GetWikiPageTitle(species)));
            }

            // Create embed pages.

            IEnumerable <Discord.Messaging.IEmbed> embedPages = EmbedUtilities.CreateEmbedPages(embed, EmbedPaginationOptions.AddPageNumbers | EmbedPaginationOptions.CopyFields);
            IPaginatedMessage paginatedMessage = new PaginatedMessage(embedPages);

            if (speciesZoneList.Count() > 0)
            {
                paginatedMessage.SetColor((await Db.GetZoneTypeAsync(speciesZoneList.GroupBy(x => x.Zone.TypeId).OrderBy(x => x.Count()).Last().Key)).Color);
            }

            if (species.IsExtinct())
            {
                paginatedMessage.SetColor(Color.Red);
            }

            return(paginatedMessage);
        }
Exemple #7
0
        private static async Task _editSpeciesPageAsync(MediaWikiClient client, EditHistory history, ISpecies species, string pageTitle, string pageContent)
        {
            if (await _editPageAsync(client, history, pageTitle, pageContent))
            {
                // If the edit was successful, associated it with this species.

                EditRecord record = await history.GetEditRecordAsync(pageTitle, pageContent);

                if (record != null)
                {
                    await history.AddEditRecordAsync(species.Id.Value, record);

                    // Because it's possible that the species was renamed, we need to look at past edits to find previous titles of the same page.
                    // Old pages for renamed species will be deleted.

                    EditRecord[] edit_records = (await history.GetEditRecordsAsync(species.Id.Value))
                                                .Where(x => x.Id != record.Id && x.Title.ToLower() != record.Title.ToLower())
                                                .ToArray();

                    // Delete all created pages where the old title does not match the current title.

                    foreach (EditRecord i in edit_records)
                    {
                        MediaWikiApiParseRequestResult parse_result = client.Parse(i.Title, new ParseParameters());

                        if (parse_result.Text.Contains(BotFlag))
                        {
                            // Only delete pages that haven't been manually edited.

                            client.Delete(i.Title, new DeleteParameters {
                                Reason = "species page moved to " + pageTitle
                            });

                            // Add an edit record for this page so that we can restore the content later without it thinking we've already made this edit.
                            // This is important, because this step can delete redirects when a page with redirects is updated. By creating a new edit record, the redirect will be recreated.

                            await history.AddEditRecordAsync(i.Title, string.Empty);
                        }
                    }

                    // We also need to delete any redirect pages that are now invalid (i.e. when specific epithet that points to a common name is changed).
                    // Delete all redirects that point to this page (or one of this page's previous titles).

                    RedirectRecord[] redirect_records = (await history.GetRedirectRecordsAsync())
                                                        .Where(i => i.Target == pageTitle || edit_records.Any(j => j.Title == i.Target)) // points to the title of this page, or one of its previous titles
                                                        .Where(i => i.Title != species.GetFullName())                                    // the title doesn't match this species' full name (the species has been renamed)
                                                        .ToArray();

                    foreach (RedirectRecord j in redirect_records)
                    {
                        MediaWikiApiParseRequestResult parse_result = client.Parse(j.Title, new ParseParameters());

                        if (parse_result.IsRedirect && parse_result.Text.Contains(BotFlag))
                        {
                            // Only delete pages that haven't been manually edited.

                            client.Delete(j.Title, new DeleteParameters {
                                Reason = "outdated redirect"
                            });
                        }
                    }
                }
            }
        }
Exemple #8
0
        private static string GeneratePictureFilenameFromSpecies(ISpecies species, string pictureUrl)
        {
            string pictureFilename = GetPictureFilenameFromPictureUrl(pictureUrl);

            return(string.Format("{0}-{1}{2}", species.GetFullName().ToLower().Replace(' ', '_'), StringUtilities.GetMD5(pictureUrl), System.IO.Path.GetExtension(pictureFilename).ToLower()));
        }