Ejemplo n.º 1
0
        internal static void LoadSettings(ulong guildId, BotVar var)
        {
            if (var.IsGeneric)
            {
                JSONContainer json = var.Generic;

                if (json.TryGetField(JSON_ENABLEDEBUG, out JSONContainer debugSettings))
                {
                    if (debugSettings.IsArray)
                    {
                        for (int i = 0; i < debugSettings.Array.Count && i < debugLogging.Length; i++)
                        {
                            debugLogging[i] = debugSettings.Array[i].Boolean;
                        }
                    }
                }
                json.TryGetField(JSON_MODERATORROLE, out AdminRole);
                json.TryGetField(JSON_WELCOMINGMESSAGE, out welcomingMessage, welcomingMessage);
                json.TryGetField(JSON_MUTEROLE, out MuteRole);
                if (json.TryGetField(JSON_CHANNELINFOS, out JSONContainer guildChannelInfoContainer))
                {
                    GuildChannelHelper.FromJSON(guildChannelInfoContainer);
                }
                if (json.TryGetArrayField(JSON_AUTOASSIGNROLEIDS, out JSONContainer autoAssignRoles))
                {
                    foreach (JSONField idField in autoAssignRoles.Array)
                    {
                        if (idField.IsNumber && !idField.IsFloat && !idField.IsSigned)
                        {
                            EventLogger.AutoAssignRoleIds.Add(idField.Unsigned_Int64);
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
 public bool ApplyJSON(JSONContainer json)
 {
     if (json.TryGetField(JSON_RED, out uint red) && json.TryGetField(JSON_GREEN, out uint green) && json.TryGetField(JSON_BLUE, out uint blue))
     {
         C = new Color((byte)red, (byte)green, (byte)blue);
         return(true);
     }
     return(false);
 }
Ejemplo n.º 3
0
 public bool FromJSON(JSONContainer json)
 {
     if (json.TryGetField(JSON_ID, out Id))
     {
         json.TryGetField(JSON_ALLOWCOMMANDS, out AllowCommands, DEFAULT_ALLOWCOMMANDS);
         json.TryGetField(JSON_ALLOWSHITPOSTING, out AllowShitposting, DEFAULT_ALLOWSHITPOSTING);
         return(true);
     }
     return(false);
 }
Ejemplo n.º 4
0
        public bool ApplyJSON(JSONContainer json)
        {
            macros.Clear();
            quotes.Clear();
            if (json.TryGetField(JSON_QUOTEID, out QuoteId) && json.TryGetArrayField(JSON_MACROS, out JSONContainer macroList) && json.TryGetArrayField(JSON_QUOTES, out JSONContainer quoteList))
            {
                foreach (JSONField macroField in macroList.Array)
                {
                    if (macroField.IsObject)
                    {
                        Macro macro = new Macro();
                        if (macro.ApplyJSON(macroField.Container))
                        {
                            macros[macro.Identifier] = macro;
                        }
                    }
                }

                foreach (JSONField quoteField in quoteList.Array)
                {
                    if (quoteField.IsObject)
                    {
                        Quote quote = new Quote();
                        if (quote.ApplyJSON(quoteField.Container))
                        {
                            quotes[quote.QuoteId] = quote;
                        }
                    }
                }

                return(true);
            }
            return(false);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initiates the GuildChannelHelpers stored configs and ids from a json object
        /// </summary>
        /// <param name="json">json data</param>
        public static void FromJSON(JSONContainer json)
        {
            channelConfigs.Clear();

            json.TryGetField(JSON_DEBUGCHANNELID, out DebugChannelId);
            json.TryGetField(JSON_WELCOMINGCHANNELID, out WelcomingChannelId);
            json.TryGetField(JSON_ADMINCOMMANDUSAGELOGCHANNELID, out AdminCommandUsageLogChannelId);
            json.TryGetField(JSON_ADMINNOTIFICATIONCHANNELID, out AdminNotificationChannelId);
            json.TryGetField(JSON_INTERACTIVEMESSAGECHANNELID, out InteractiveMessagesChannelId);
            json.TryGetField(JSON_GUILDCATEGORYID, out GuildCategoryId);

            if (json.TryGetField(JSON_CHANNELINFOS, out IReadOnlyList <JSONField> channelInfos))
            {
                foreach (JSONField channelInfo in channelInfos)
                {
                    if (channelInfo.IsObject)
                    {
                        GuildChannelConfiguration info = new GuildChannelConfiguration();
                        if (info.FromJSON(channelInfo.Container))
                        {
                            channelConfigs.Add(info.Id, info);
                        }
                    }
                }
            }
        }
Ejemplo n.º 6
0
 public bool ApplyJSON(JSONContainer json)
 {
     if (json.TryGetField(JSON_ALLOWCMDS, out AllowCommands) && json.TryGetField(JSON_ALLOWSHITPOSTING, out AllowShitposting))
     {
         if (json.TryGetArrayField(JSON_ALLOWEDCOLL, out JSONContainer collArray))
         {
             foreach (JSONField field in collArray.Array)
             {
                 if (field.IsString)
                 {
                     allowedCommandCollections.Add(field.String);
                 }
             }
         }
         return(true);
     }
     return(false);
 }
Ejemplo n.º 7
0
        public bool FromJSON(JSONContainer json)
        {
            MemberIds.Clear();

            if (json.TryGetField(JSON_CHANNELIDS, out ChannelId) && json.TryGetField(JSON_ROLEID, out RoleId) && json.TryGetField(JSON_CAPTAINID, out CaptainId) && json.TryGetField(JSON_MEMBERIDS, out IReadOnlyList <JSONField> memberIdList))
            {
                json.TryGetField(JSON_ACTIVE, out Active, Active);
                foreach (JSONField memberIdJson in memberIdList)
                {
                    if (memberIdJson.IsNumber && !memberIdJson.IsSigned && !memberIdJson.IsFloat && !MemberIds.Contains(memberIdJson.Unsigned_Int64) && memberIdJson.Unsigned_Int64 != CaptainId)
                    {
                        MemberIds.Add(memberIdJson.Unsigned_Int64);
                    }
                }
                if (json.TryGetField(JSON_MATEIDS, out IReadOnlyList <JSONField> mateIdList))
                {
                    foreach (JSONField mateIdJson in mateIdList)
                    {
                        if (mateIdJson.IsNumber && !mateIdJson.IsSigned && !mateIdJson.IsFloat && !MateIds.Contains(mateIdJson.Unsigned_Int64))
                        {
                            MateIds.Add(mateIdJson.Unsigned_Int64);
                            if (MemberIds.Contains(mateIdJson.Unsigned_Int64))
                            {
                                MemberIds.Remove(mateIdJson.Unsigned_Int64);
                            }
                        }
                    }
                }
                if (json.TryGetField(JSON_FOUNDINGTIMESTAMP, out string timestamp_str))
                {
                    if (!DateTimeOffset.TryParseExact(timestamp_str, "u", CultureInfo.InvariantCulture, DateTimeStyles.None, out FoundingTimestamp))
                    {
                        FoundingTimestamp = DateTimeOffset.MinValue;
                    }
                }

                TryFindNameAndColor();

                return(true);
            }
            return(false);
        }
Ejemplo n.º 8
0
        private Dictionary <string, System> GetNames(JSONContainer json)
        {
            Dictionary <string, System> result = new Dictionary <string, System>(json.Array.Count);

            foreach (JSONField systemField in json.Array)
            {
                if (systemField.IsObject)
                {
                    JSONContainer systemJSON = systemField.Container;
                    if (systemJSON.TryGetField("name", out string name) && systemJSON.TryGetField("distance", out double distance))
                    {
                        result.Add(name, new System()
                        {
                            Name = name, Distance = distance
                        });
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 9
0
        private static EmbedBuilder getEmbed(JSONContainer embedJSON)
        {
            EmbedBuilder embed = new EmbedBuilder
            {
                Title        = getLengthCheckedStringField(embedJSON, TITLE, EMBEDTITLE_MAX, "The embed title may not exceed {0} characters!"),
                Description  = getLengthCheckedStringField(embedJSON, DESCRIPTION, EMBEDDESCRIPTION_MAX, "The embed description may not exceed {0} characters!"),
                Url          = getFormCheckedURLField(embedJSON, URL, "The embed URL is not a well formed URL!"),
                Timestamp    = getParsedTimestampField(embedJSON, TIMESTAMP, "Could not parse the timestamp to a DateTimeOffset"),
                ThumbnailUrl = getFormCheckedImageField(embedJSON, THUMBNAIL, "The URL for the embed thumbnail is not a well formed URL!"),
                ImageUrl     = getFormCheckedImageField(embedJSON, IMAGE, "The url for the embed image is not a well formed url!")
            };

            if (embedJSON.TryGetField(AUTHOR, out JSONContainer authorJSON))
            {
                embed.Author = getAuthor(authorJSON);
            }

            if (embedJSON.TryGetField(COLOR, out int color))
            {
                embed.Color = new Color((uint)color);
            }

            if (embedJSON.TryGetField(FOOTER, out JSONContainer footerJSON))
            {
                embed.Footer = getFooter(footerJSON);
            }

            if (embedJSON.TryGetField(FIELDS, out IReadOnlyList <JSONField> fieldsJSON))
            {
                embed.Fields = getEmbedFields(fieldsJSON);
            }

            // Length check

            if (embed.Length > EMBEDTOTALLENGTH_MAX)
            {
                throw new EmbedParseException($"The total length of the embed may not exceed {EMBEDTOTALLENGTH_MAX} characters!");
            }

            return(embed);
        }
Ejemplo n.º 10
0
 public bool FromJSON(JSONContainer json)
 {
     if (json.TryGetField(JSON_MODTYPE, out uint type) && json.TryGetField(JSON_CHANNELID, out ulong channelId) && json.TryGetField(JSON_ACTORID, out ulong actorid))
     {
         Type      = (ChannelModerationType)type;
         ChannelId = channelId;
         ActorId   = actorid;
         if (json.TryGetField(JSON_TIMESTAMP, out string timestamp_str))
         {
             if (DateTimeOffset.TryParseExact(timestamp_str, "u", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTimeOffset timestamp))
             {
                 Timestamp = timestamp;
             }
             else
             {
                 Timestamp = DateTimeOffset.MinValue;
             }
         }
         json.TryGetField(JSON_CHANNELNAME, out string channelname);
         ChannelName = channelname;
         json.TryGetField(JSON_ACTORNAME, out string actorname);
         ActorName = actorname;
         json.TryGetField(JSON_INFO, out string info);
         Info = info;
         return(true);
     }
     return(false);
 }
Ejemplo n.º 11
0
 public bool ApplyJSON(JSONContainer json)
 {
     if (json.TryGetField(JSON_ID, out QuoteId) && json.TryGetField(JSON_CONTENT, out MessageContent) && json.TryGetField(JSON_TIMESTAMP, out string timestamp_str) && json.TryGetField(JSON_GUILD_ID, out GuildId))
     {
         json.TryGetField(JSON_AUTHOR_ID, out AuthorId);
         json.TryGetField(JSON_AUTHOR_NAME, out AuthorName, "Unknown Author");
         json.TryGetField(JSON_CHANNEL_NAME, out ChannelName, "Unknown Channel");
         json.TryGetField(JSON_MESSAGE_ID, out MessageId);
         json.TryGetField(JSON_CHANNEL_ID, out ChannelId);
         json.TryGetField(JSON_IMAGE_URL, out ImageURL, string.Empty);
         return(DateTimeOffset.TryParseExact(timestamp_str, "u", CultureInfo.InvariantCulture, DateTimeStyles.None, out Timestamp));
     }
     return(false);
 }
Ejemplo n.º 12
0
 private static string getLengthCheckedStringField(JSONContainer json, string identifier, int maxlength, string errorstring)
 {
     if (json.TryGetField(identifier, out string str))
     {
         if (!string.IsNullOrEmpty(str))
         {
             if (str.Length > maxlength)
             {
                 throw new EmbedParseException(string.Format(errorstring, maxlength));
             }
             return(str);
         }
     }
     return(null);
 }
Ejemplo n.º 13
0
        public bool FromJSON(JSONContainer json)
        {
            if (json.TryGetField(JSON_TYPE, out int type_i) && json.TryGetField(JSON_ACTORID, out ulong actorId))
            {
                Type    = (ModerationType)type_i;
                ActorId = actorId;

                if (json.TryGetField(JSON_TIMESTAMP, out string timestamp_str))
                {
                    if (DateTimeOffset.TryParseExact(timestamp_str, "u", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTimeOffset timestamp))
                    {
                        Timestamp = timestamp;
                    }
                    else
                    {
                        Timestamp = DateTimeOffset.MinValue;
                    }
                }

                if (json.TryGetField(JSON_DESCR, out string descr))
                {
                    Reason = descr;
                }
                else
                {
                    Reason = null;
                }

                if (json.TryGetField(JSON_INFO, out string info))
                {
                    Info = info;
                }
                else
                {
                    Info = null;
                }

                if (json.TryGetField(JSON_ACTORNAME, out string actorname))
                {
                    ActorName = actorname;
                }
                else
                {
                    ActorName = null;
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 14
0
 private static DateTimeOffset?getParsedTimestampField(JSONContainer json, string identifier, string error)
 {
     if (json.TryGetField(identifier, out string timestamp_str))
     {
         if (!string.IsNullOrEmpty(timestamp_str))
         {
             if (DateTimeOffset.TryParse(timestamp_str, out DateTimeOffset timestamp))
             {
                 return(timestamp);
             }
             else
             {
                 throw new EmbedParseException(error);
             }
         }
     }
     return(null);
 }
Ejemplo n.º 15
0
 private static string getFormCheckedURLField(JSONContainer json, string identifier, string errorstring)
 {
     if (json.TryGetField(identifier, out string embedURL))
     {
         if (!string.IsNullOrEmpty(embedURL))
         {
             if (Uri.IsWellFormedUriString(embedURL, UriKind.Absolute))
             {
                 return(embedURL);
             }
             else
             {
                 throw new EmbedParseException(errorstring);
             }
         }
     }
     return(null);
 }
Ejemplo n.º 16
0
        internal bool FromJSON(JSONContainer json)
        {
            if (json.TryGetField(JSON_ID, out Identifier) && json.TryGetField(JSON_TYPE, out int type))
            {
                Type = (BotVarType)type;
                switch (Type)
                {
                case BotVarType.Undefined:
                    return(true);

                case BotVarType.UInt64:
                    return(json.TryGetField(JSON_VALUE, out UInt64));

                case BotVarType.Int64:
                    return(json.TryGetField(JSON_VALUE, out Int64));

                case BotVarType.Float64:
                    return(json.TryGetField(JSON_VALUE, out Float64));

                case BotVarType.String:
                    return(json.TryGetField(JSON_VALUE, out String));

                case BotVarType.Bool:
                    return(json.TryGetField(JSON_VALUE, out Bool));

                case BotVarType.Generic:
                    return(json.TryGetField(JSON_VALUE, out Generic));

                default:
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 17
0
 public bool FromJSON(JSONContainer json)
 {
     if (json.TryGetField(JSON_CHANNELID, out ChannelId))
     {
         if (json.TryGetArrayField(JSON_MODENTRIES, out JSONContainer jsonModEntries))
         {
             foreach (JSONField field in jsonModEntries.Array)
             {
                 if (field.IsObject)
                 {
                     ChannelModerationEntry entry = new ChannelModerationEntry(Parent.GuildId);
                     if (entry.FromJSON(field.Container))
                     {
                         moderationEntries.Add(entry);
                     }
                 }
             }
         }
         return(true);
     }
     return(false);
 }
Ejemplo n.º 18
0
            public void FromJSON(JSONContainer json)
            {
                json.TryGetField("name", out Name, Name);
                json.TryGetField("id", out Id);
                if (json.TryGetField("requirePermit", out RequirePermit))
                {
                    if (RequirePermit == true)
                    {
                        json.TryGetField("permitName", out PermitName, "Unknown Permit");
                    }
                }

                if (json.TryGetObjectField("information", out JSONContainer infoJSON))
                {
                    json.TryGetField("security", out Security, "Anarchy");
                    json.TryGetField("faction", out ControllingFaction);
                }
            }
Ejemplo n.º 19
0
        private EmbedBuilder GetSystemInfoEmbed(JSONContainer systemJSON, JSONContainer stationsJSON, JSONContainer trafficJSON, JSONContainer deathsJSON, out List <EmbedFieldBuilder> allStations)
        {
            EmbedBuilder systemembed = new EmbedBuilder();

            allStations = new List <EmbedFieldBuilder>();
            bool stationsFound = false;

            if (systemJSON.TryGetField("name", out string system_name, string.Empty) && systemJSON.TryGetField("id", out ulong system_id, 0))
            {
                // Gathering Information

                // Gathering General System information
                string system_name_link = system_name.Replace(' ', '+');
                string security         = "Unknown";
                if (systemJSON.TryGetObjectField("information", out JSONContainer system_information))
                {
                    system_information.TryGetField("security", out security, "Anarchy (Unpopulated)");
                }
                string startype = "Not found";
                if (systemJSON.TryGetObjectField("primaryStar", out JSONContainer primaryStar))
                {
                    primaryStar.TryGetField("type", out startype, startype);
                    if (systemJSON.TryGetField("isScoopable", out bool scoopable))
                    {
                        if (!scoopable)
                        {
                            startype += " **(Unscoopable)**";
                        }
                    }
                }
                systemJSON.TryGetField("requirePermit", out bool system_requirepermit, false);
                systemJSON.TryGetField("permitName", out string system_permit, "Unknown Permit");

                // Gathering information about stations
                StationInfo        bestOrbitalLarge  = null;
                StationInfo        bestOrbitalMedium = null;
                StationInfo        bestPlanetary     = null;
                List <StationInfo> stationInfos      = new List <StationInfo>();
                if ((stationsJSON != null) && stationsJSON.TryGetArrayField("stations", out stationsJSON))
                {
                    stationsFound = true;
                    foreach (JSONField station in stationsJSON.Array)
                    {
                        StationInfo info = new StationInfo();
                        if (info.FromJSON(station.Container))
                        {
                            stationInfos.Add(info);
                            if (info.HasLargePadOrbital)
                            {
                                if (bestOrbitalLarge == null)
                                {
                                    bestOrbitalLarge = info;
                                }
                                else
                                if (info.Distance < bestOrbitalLarge.Distance)
                                {
                                    bestOrbitalLarge = info;
                                }
                            }
                            if (info.HasMedPadOrbital)
                            {
                                if (bestOrbitalMedium == null)
                                {
                                    bestOrbitalMedium = info;
                                }
                                else
                                if (info.Distance < bestOrbitalMedium.Distance)
                                {
                                    bestOrbitalMedium = info;
                                }
                            }
                            if (info.IsPlanetary)
                            {
                                if (bestPlanetary == null)
                                {
                                    bestPlanetary = info;
                                }
                                else if (info.Distance < bestPlanetary.Distance)
                                {
                                    bestPlanetary = info;
                                }
                            }
                        }
                    }
                }

                // Getting Information about traffic
                int traffic_week = -1;
                int traffic_day  = -1;

                if ((trafficJSON != null) && trafficJSON.TryGetObjectField("traffic", out trafficJSON))
                {
                    trafficJSON.TryGetField("week", out traffic_week, -1);
                    trafficJSON.TryGetField("day", out traffic_day, -1);
                }

                // Getting Information about CMDR deaths
                int deaths_week = -1;
                int deaths_day  = -1;

                if ((deathsJSON != null) && deathsJSON.TryGetObjectField("deaths", out deathsJSON))
                {
                    deathsJSON.TryGetField("week", out deaths_week, -1);
                    deathsJSON.TryGetField("day", out deaths_day, -1);
                }

                // Constructing message
                systemembed.Color = BotCore.EmbedColor;
                systemembed.Title = $"__**System Info for {system_name}**__";
                systemembed.Url   = $"https://www.edsm.net/en/system/id/{system_id}/name/{system_name_link}";
                systemembed.AddField("General Info", $"{(system_requirepermit ? string.Format("**Requires Permit**: {0}\n", system_permit) : string.Empty)}Star Type: {startype}\nSecurity: {security}");

                bool provideInfoOnLarge     = bestOrbitalLarge != null;
                bool provideInfoOnMedium    = (!provideInfoOnLarge && bestOrbitalMedium != null) || (provideInfoOnLarge && bestOrbitalMedium != null && bestOrbitalLarge.Distance > bestOrbitalMedium.Distance);
                bool provideInfoOnPlanetary = (!provideInfoOnLarge && bestPlanetary != null) || (provideInfoOnLarge && bestPlanetary != null && bestOrbitalLarge.Distance > bestPlanetary.Distance);
                if (provideInfoOnLarge)
                {
                    systemembed.AddField("Closest Orbital Large Pad", bestOrbitalLarge.ToString());
                }
                if (provideInfoOnMedium)
                {
                    systemembed.AddField("Closest Orbital Medium Pad", bestOrbitalMedium.ToString());
                }
                if (provideInfoOnPlanetary)
                {
                    systemembed.AddField("Closest Planetary Large Pad", bestPlanetary.ToString());
                }
                if (!provideInfoOnLarge && !provideInfoOnMedium && !provideInfoOnPlanetary)
                {
                    systemembed.AddField("No Stations in this System!", "- / -");
                }
                if (traffic_day != -1 && traffic_week != -1)
                {
                    systemembed.AddField("Traffic Report", string.Format("Last 7 days: {0} CMDRs, last 24 hours: {1} CMDRs", traffic_week, traffic_day));
                }
                else
                {
                    systemembed.AddField("No Traffic Report Available", "- / -");
                }
                if (deaths_day != -1 && deaths_week != -1)
                {
                    systemembed.AddField("CMDR Deaths Report", string.Format("Last 7 days: {0} CMDRs, last 24 hours: {1} CMDRs", deaths_week, deaths_day));
                }
                else
                {
                    systemembed.AddField("No CMDR Deaths Report Available", "- / -");
                }

                if (stationsFound)
                {
                    foreach (StationInfo stationInfo in stationInfos)
                    {
                        allStations.Add(Macros.EmbedField(stationInfo.Title_NoLink, stationInfo.Services_Link));
                    }
                }
            }
Ejemplo n.º 20
0
 public bool ApplyJSON(JSONContainer json)
 {
     return(json.TryGetField(JSON_GUILDID, out GuildId) && json.TryGetField(JSON_CHANNELID, out ChannelId));
 }
Ejemplo n.º 21
0
        public static ArgumentParseResult TryParseEmbedFromJSONObject(JSONContainer json, out EmbedBuilder embed, out string messageContent)
        {
            embed          = null;
            messageContent = null;

            json.TryGetField(MESSAGECONTENT, out JSONField messageContentJSON);
            json.TryGetField(EMBED, out JSONContainer embedJSON);

            if (messageContentJSON == null && embedJSON == null)
            {
                return(new ArgumentParseResult("Neither message nor embed could be found!"));
            }

            if ((messageContentJSON != null) && messageContentJSON.IsString)
            {
                if (!string.IsNullOrEmpty(messageContentJSON.String))
                {
                    if (messageContentJSON.String.Length > MESSAGECONTENT_MAX)
                    {
                        return(new ArgumentParseResult($"The message content may not exceed {MESSAGECONTENT_MAX} characters!"));
                    }
                    messageContent = messageContentJSON.String;
                }
            }
            else
            {
                messageContent = string.Empty;
            }

            if (embedJSON != null)
            {
                embed = new EmbedBuilder();

                // Parse TITLE, DESCRIPTION, TITLE_URL, TIMESTAMP

                if (embedJSON.TryGetField(TITLE, out string embedTitle))
                {
                    if (!string.IsNullOrEmpty(embedTitle))
                    {
                        if (embedTitle.Length > EMBEDTITLE_MAX)
                        {
                            return(new ArgumentParseResult($"The embed title may not exceed {EMBEDTITLE_MAX} characters!"));
                        }
                        embed.Title = embedTitle;
                    }
                }
                if (embedJSON.TryGetField(DESCRIPTION, out string embedDescription))
                {
                    if (!string.IsNullOrEmpty(embedDescription))
                    {
                        if (embedDescription.Length > EMBEDDESCRIPTION_MAX)
                        {
                            return(new ArgumentParseResult($"The embed title may not exceed {EMBEDDESCRIPTION_MAX} characters!"));
                        }
                        embed.Description = embedDescription;
                    }
                }
                if (embedJSON.TryGetField(URL, out string embedURL))
                {
                    if (!string.IsNullOrEmpty(embedURL))
                    {
                        if (Uri.IsWellFormedUriString(embedURL, UriKind.Absolute))
                        {
                            embed.Url = embedURL;
                        }
                        else
                        {
                            return(new ArgumentParseResult("The url for the embed title is not a well formed url!"));
                        }
                    }
                }
                if (embedJSON.TryGetField(TIMESTAMP, out string embedFooterTimestamp))
                {
                    if (!string.IsNullOrEmpty(embedFooterTimestamp))
                    {
                        if (DateTimeOffset.TryParse(embedFooterTimestamp, out DateTimeOffset timestamp))
                        {
                            embed.Timestamp = timestamp;
                        }
                        else
                        {
                            return(new ArgumentParseResult("Could not parse the timestamp to a DateTimeOffset"));
                        }
                    }
                }

                // Parse AUTHOR

                if (embedJSON.TryGetField(AUTHOR, out JSONContainer authorJSON))
                {
                    EmbedAuthorBuilder author = new EmbedAuthorBuilder();

                    if (authorJSON.TryGetField(NAME, out string authorName))
                    {
                        if (!string.IsNullOrEmpty(authorName))
                        {
                            if (authorName.Length > EMBEDAUTHORNAME_MAX)
                            {
                                return(new ArgumentParseResult($"The embed author name may not exceed {EMBEDAUTHORNAME_MAX} characters!"));
                            }
                            author.Name = authorName;
                        }
                    }
                    if (authorJSON.TryGetField(ICON_URL, out string authorIconUrl))
                    {
                        if (!string.IsNullOrEmpty(authorIconUrl))
                        {
                            author.IconUrl = authorIconUrl;
                        }
                    }
                    if (authorJSON.TryGetField(URL, out string authorUrl))
                    {
                        if (!string.IsNullOrEmpty(authorUrl))
                        {
                            author.Url = authorUrl;
                        }
                    }

                    embed.Author = author;
                }

                // Parse THUMBNAIL, IMAGE

                if (embedJSON.TryGetField(THUMBNAIL, out JSONContainer thumbnailJSON))
                {
                    if (thumbnailJSON.TryGetField(URL, out string thumbnailUrl))
                    {
                        if (Uri.IsWellFormedUriString(thumbnailUrl, UriKind.Absolute))
                        {
                            embed.ThumbnailUrl = thumbnailUrl;
                        }
                        else
                        {
                            return(new ArgumentParseResult("The url for the embed thumbnail is not a well formed url!"));
                        }
                    }
                }
                if (embedJSON.TryGetField(IMAGE, out JSONContainer imageJSON))
                {
                    if (imageJSON.TryGetField(URL, out string imageUrl))
                    {
                        if (Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
                        {
                            embed.ImageUrl = imageUrl;
                        }
                        else
                        {
                            return(new ArgumentParseResult("The url for the embed image is not a well formed url!"));
                        }
                    }
                }

                // Parse Color

                if (embedJSON.TryGetField(COLOR, out int color))
                {
                    Discord.Color embedColor = new Color((uint)color);
                    embed.Color = embedColor;
                }

                // Parse Footer

                if (embedJSON.TryGetField(FOOTER, out JSONContainer footerJSON))
                {
                    EmbedFooterBuilder footer = new EmbedFooterBuilder();

                    if (footerJSON.TryGetField(TEXT, out string footerText))
                    {
                        if (!string.IsNullOrEmpty(footerText))
                        {
                            if (footerText.Length > EMBEDFOOTERTEXT_MAX)
                            {
                                return(new ArgumentParseResult($"The embed footer text may not exceed {EMBEDFOOTERTEXT_MAX} characters!"));
                            }
                            footer.Text = footerText;
                        }
                    }
                    if (footerJSON.TryGetField(ICON_URL, out string footerIconUrl))
                    {
                        if (!string.IsNullOrEmpty(footerIconUrl))
                        {
                            if (Uri.IsWellFormedUriString(footerIconUrl, UriKind.Absolute))
                            {
                                footer.IconUrl = footerIconUrl;
                            }
                            else
                            {
                                return(new ArgumentParseResult("The url for the embed footer icon is not a well formed url!"));
                            }
                        }
                    }

                    embed.Footer = footer;
                }

                // Parse Fields

                if (embedJSON.TryGetField(FIELDS, out IReadOnlyList <JSONField> fieldsList))
                {
                    if (fieldsList.Count > EMBEDFIELDCOUNT_MAX)
                    {
                        return(new ArgumentParseResult($"The embed can not have more than {EMBEDFIELDCOUNT_MAX} fields!"));
                    }
                    foreach (JSONField fieldJSON in fieldsList)
                    {
                        if (fieldJSON.IsObject && fieldJSON.Container != null)
                        {
                            if (fieldJSON.Container.TryGetField(NAME, out string fieldName) && fieldJSON.Container.TryGetField(VALUE, out string fieldValue))
                            {
                                fieldJSON.Container.TryGetField(INLINE, out bool fieldInline, false);
                                if (fieldName != null && fieldValue != null)
                                {
                                    if (fieldName.Length > EMBEDFIELDNAME_MAX)
                                    {
                                        return(new ArgumentParseResult($"A field name may not exceed {EMBEDFIELDNAME_MAX} characters!"));
                                    }
                                    if (fieldValue.Length > EMBEDFIELDVALUE_MAX)
                                    {
                                        return(new ArgumentParseResult($"A field value may not exceed {EMBEDFIELDVALUE_MAX} characters!"));
                                    }
                                    embed.AddField(fieldName, fieldValue, fieldInline);
                                }
                            }
                        }
                    }
                }

                if (embed.Length > EMBEDTOTALLENGTH_MAX)
                {
                    return(new ArgumentParseResult($"The total length of the embed may not exceed {EMBEDTOTALLENGTH_MAX} characters!"));
                }
            }

            return(ArgumentParseResult.SuccessfullParse);
        }
Ejemplo n.º 22
0
 public bool ApplyJSON(JSONContainer json)
 {
     JSON = json;
     return json.TryGetField(JSON_ID, out Identifier) && (json.HasField(EmbedHelper.MESSAGECONTENT) || json.HasField(EmbedHelper.EMBED));
 }
Ejemplo n.º 23
0
 internal bool RetrieveId(JSONContainer json)
 {
     return(json.TryGetField("Id", out Id));
 }
Ejemplo n.º 24
0
        private EmbedBuilder GetEDSMCMDREmbed(JSONContainer json, string backupName)
        {
            EmbedBuilder result;

            if (json.TryGetField("msg", out string msg))
            {
                if (msg == "OK")
                {
                    string system_link     = null;
                    bool   system_id_found = json.TryGetField("systemId", out uint system_id, 0);
                    if (json.TryGetField("system", out string system_name, null) && system_id_found)
                    {
                        system_link = $"https://www.edsm.net/en/system/id/{system_id}/name/{system_name.Replace(' ', '+')}";
                    }
                    string user_name = backupName;
                    if (json.TryGetField("url", out string profile_url, "https://www.edsm.net"))
                    {
                        string[] urlsections = profile_url.Split('/');
                        if (urlsections.Length > 1)
                        {
                            user_name = urlsections[urlsections.Length - 1];
                        }
                    }
                    json.TryGetField("shipType", out string shipType, null);
                    string station_name = null;
                    string station_link = null;
                    if (json.TryGetField("isDocked", out bool isDocked, false))
                    {
                        json.TryGetField("station", out station_name, "Unknown Station");
                        if (json.TryGetField("stationId", out uint station_id) && system_link != null)
                        {
                            station_link = $"https://www.edsm.net/en/system/stations/id/{system_id}/name/{system_name.Replace(' ', '+')}/details/idS/{station_id}/nameS/{station_name.Replace(' ', '+')}";
                        }
                    }

                    result = new EmbedBuilder()
                    {
                        Author = new EmbedAuthorBuilder()
                        {
                            Url  = profile_url,
                            Name = $"{user_name}'s EDSM Profile"
                        },
                        Color = BotCore.EmbedColor
                    };
                    if (system_name != null)
                    {
                        if (system_link != null)
                        {
                            result.AddField("System", $"[{system_name}]({system_link})");
                        }
                        else
                        {
                            result.AddField("System", system_name);
                        }
                    }
                    if (shipType != null)
                    {
                        result.AddField("Ship", shipType);
                    }
                    if (isDocked)
                    {
                        if (station_link != null)
                        {
                            result.AddField("Docked At", $"[{station_name}]({station_link})");
                        }
                        else
                        {
                            result.AddField("Docked At", station_name);
                        }
                    }
                }
                else
                {
                    result = new EmbedBuilder()
                    {
                        Author = new EmbedAuthorBuilder()
                        {
                            Name = backupName
                        },
                        Color       = BotCore.ErrorColor,
                        Description = msg
                    };
                }
            }
            else
            {
                result = new EmbedBuilder()
                {
                    Author = new EmbedAuthorBuilder()
                    {
                        Name = backupName
                    },
                    Color       = BotCore.ErrorColor,
                    Description = $"Internal Error - {Macros.GetCodeLocation()}"
                };
            }
            return(result);
        }
Ejemplo n.º 25
0
        private EmbedBuilder GetInaraCMDREmbed(JSONContainer json, string backupName)
        {
            EmbedBuilder result;

            if (json.TryGetArrayField("events", out JSONContainer arrayJSON))
            {
                if (arrayJSON.Array.Count >= 1 && arrayJSON.Array[0].IsObject)
                {
                    JSONContainer eventJSON = arrayJSON.Array[0].Container;
                    if (eventJSON.TryGetField("eventStatus", out uint eventStatusId))
                    {
                        eventJSON.TryGetField("eventStatusText", out string eventStatusText);
                        if (eventStatusId == 204)
                        {
                            result = new EmbedBuilder()
                            {
                                Author = new EmbedAuthorBuilder()
                                {
                                    Name = backupName
                                },
                                Color       = BotCore.ErrorColor,
                                Description = eventStatusText
                            };
                        }
                        else if (eventJSON.TryGetObjectField("eventData", out JSONContainer cmdrJSON))
                        {
                            if (cmdrJSON.TryGetField("userName", out string user_name))
                            {
                                if (eventStatusId == 202 && !user_name.Equals(backupName, StringComparison.OrdinalIgnoreCase) && cmdrJSON.TryGetArrayField("otherNamesFound", out JSONContainer otherNamesArray))
                                {
                                    result = new EmbedBuilder()
                                    {
                                        Title       = "Multiple Results found!",
                                        Description = $"{user_name}\n{otherNamesArray.Array.OperationJoinReadonly("\n", field => { return field.String; })}"
                                    };
                                }
                                else
                                {
                                    cmdrJSON.TryGetField("inaraURL", out string cmdr_url);
                                    result = new EmbedBuilder()
                                    {
                                        Author = new EmbedAuthorBuilder()
                                        {
                                            Name = $"{user_name}'s Inara Profile",
                                            Url  = cmdr_url
                                        },
                                        Color = BotCore.EmbedColor
                                    };
                                    if (cmdrJSON.TryGetField("preferredGameRole", out string cmdr_gamerole))
                                    {
                                        result.AddField("Game Role", cmdr_gamerole, true);
                                    }
                                    if (cmdrJSON.TryGetField("preferredAllegianceName", out string cmdr_allegiance))
                                    {
                                        result.AddField("Allegiance", cmdr_allegiance, true);
                                    }
                                    if (cmdrJSON.TryGetObjectField("commanderSquadron", out JSONContainer squadronJSON))
                                    {
                                        squadronJSON.TryGetField("squadronName", out string squadron_name);
                                        squadronJSON.TryGetField("squadronMemberRank", out string squadron_rank);
                                        squadronJSON.TryGetField("squadronMembersCount", out uint squadron_membercount);
                                        if (squadronJSON.TryGetField("inaraURL", out string squadron_link))
                                        {
                                            result.AddField("Squadron", $"[{squadron_name}]({squadron_link}) ({squadron_membercount} Members): Rank `{squadron_rank}`", true);
                                        }
                                        else
                                        {
                                            result.AddField("Squadron", $"{squadron_name} ({squadron_membercount} Members): Rank `{squadron_rank}`", true);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                result = InaraErrorEmbed(backupName);
                            }
                        }
                        else
                        {
                            result = InaraErrorEmbed(backupName);
                        }
                    }
                    else
                    {
                        result = InaraErrorEmbed(backupName);
                    }
                }
                else
                {
                    result = InaraErrorEmbed(backupName);
                }
            }
            else
            {
                result = InaraErrorEmbed(backupName);
            }

            return(result);
        }
Ejemplo n.º 26
0
        public bool FromJSON(JSONContainer json)
        {
            if (json.TryGetField(JSON_USERID, out ulong id))
            {
                UserId = id;
            }
            else
            {
                return(false);
            }

            string timestamp_str;

            if (json.TryGetField(JSON_BANNEDUNTIL, out timestamp_str))
            {
                if (DateTimeOffset.TryParseExact(timestamp_str, "u", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTimeOffset bannedUntil))
                {
                    BannedUntil = bannedUntil;
                }
                else
                {
                    BannedUntil = DateTimeOffset.MaxValue;
                }
            }
            else
            {
                BannedUntil = null;
            }
            if (json.TryGetField(JSON_MUTEDUNTIL, out timestamp_str))
            {
                if (DateTimeOffset.TryParseExact(timestamp_str, "u", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTimeOffset mutedUntil))
                {
                    MutedUntil = mutedUntil;
                }
                else
                {
                    MutedUntil = DateTimeOffset.MaxValue;
                }
                if (json.TryGetField(JSON_ROLEIDS, out JSONContainer roleArray))
                {
                    rolesPreMute = new List <ulong>();
                    if (roleArray.IsArray && roleArray.Array != null)
                    {
                        foreach (JSONField arrayField in roleArray.Array)
                        {
                            if (arrayField.IsNumber && !arrayField.IsFloat)
                            {
                                rolesPreMute.Add(arrayField.Unsigned_Int64);
                            }
                        }
                    }
                }
            }
            else
            {
                MutedUntil = null;
            }

            if (json.TryGetArrayField(JSON_MODENTRIES, out JSONContainer jsonModEntries))
            {
                if (jsonModEntries.Array != null)
                {
                    foreach (JSONField jsonModEntry in jsonModEntries.Array)
                    {
                        if (jsonModEntry.IsObject)
                        {
                            UserModerationEntry moderationEntry = new UserModerationEntry(Parent.GuildId);
                            if (moderationEntry.FromJSON(jsonModEntry.Container))
                            {
                                moderationEntries.Add(moderationEntry);
                            }
                        }
                    }
                }
            }

            return(BannedUntil != null || MutedUntil != null || moderationEntries.Count > 0);
        }