Skip to content

Commit

Permalink
Replace (almost) all parsable enums to an enum-like class (#665)
Browse files Browse the repository at this point in the history
Co-authored-by: Abitofevrything <[email protected]>
  • Loading branch information
Lexedia and abitofevrything committed Jul 7, 2024
1 parent 10fdecc commit 672cd3d
Show file tree
Hide file tree
Showing 48 changed files with 638 additions and 1,044 deletions.
5 changes: 3 additions & 2 deletions lib/src/gateway/gateway.dart
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ class Gateway extends GatewayManager with EventParser {
guildId: guildId,
action: client.guilds[guildId].autoModerationRules.parseAutoModerationAction(raw['action'] as Map<String, Object?>),
ruleId: Snowflake.parse(raw['rule_id']!),
triggerType: TriggerType.parse(raw['rule_trigger_type'] as int),
triggerType: TriggerType(raw['rule_trigger_type'] as int),
userId: Snowflake.parse(raw['user_id']!),
channelId: maybeParse(raw['channel_id'], Snowflake.parse),
messageId: maybeParse(raw['message_id'], Snowflake.parse),
Expand Down Expand Up @@ -951,7 +951,7 @@ class Gateway extends GatewayManager with EventParser {
(Map<String, Object?> raw) => PartialUser(id: Snowflake.parse(raw['id']!), manager: client.users),
),
guildId: maybeParse(raw['guild_id'], Snowflake.parse),
status: maybeParse(raw['status'], UserStatus.parse),
status: maybeParse(raw['status'], UserStatus.new),
activities: maybeParseMany(raw['activities'], parseActivity),
clientStatus: maybeParse(raw['client_status'], parseClientStatus),
);
Expand Down Expand Up @@ -1029,6 +1029,7 @@ class Gateway extends GatewayManager with EventParser {
InteractionType.modalSubmit => InteractionCreateEvent<ModalSubmitInteraction>(gateway: this, interaction: interaction as ModalSubmitInteraction),
InteractionType.applicationCommandAutocomplete =>
InteractionCreateEvent<ApplicationCommandAutocompleteInteraction>(gateway: this, interaction: interaction as ApplicationCommandAutocompleteInteraction),
InteractionType() => throw StateError('Unknown interaction type: ${interaction.type}'),
} as InteractionCreateEvent<Interaction<dynamic>>;
}

Expand Down
12 changes: 6 additions & 6 deletions lib/src/http/managers/application_command_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ abstract class ApplicationCommandManager extends Manager<ApplicationCommand> {
return ApplicationCommand(
id: Snowflake.parse(raw['id']!),
manager: this,
type: ApplicationCommandType.parse(raw['type'] as int? ?? 1),
type: ApplicationCommandType(raw['type'] as int? ?? 1),
applicationId: Snowflake.parse(raw['application_id']!),
guildId: maybeParse(raw['guild_id'], Snowflake.parse),
name: raw['name'] as String,
Expand All @@ -59,16 +59,16 @@ abstract class ApplicationCommandManager extends Manager<ApplicationCommand> {
defaultMemberPermissions: maybeParse(raw['default_member_permissions'], (String raw) => Permissions(int.parse(raw))),
hasDmPermission: raw['dm_permission'] as bool?,
isNsfw: raw['nsfw'] as bool?,
integrationTypes: maybeParseMany(raw['integration_types'], ApplicationIntegrationType.parse) ?? [ApplicationIntegrationType.guildInstall],
contexts: maybeParseMany(raw['contexts'], InteractionContextType.parse),
integrationTypes: maybeParseMany(raw['integration_types'], ApplicationIntegrationType.new) ?? [ApplicationIntegrationType.guildInstall],
contexts: maybeParseMany(raw['contexts'], InteractionContextType.new),
version: Snowflake.parse(raw['version']!),
);
}

/// Parse a [CommandOption] from [raw].
CommandOption parseApplicationCommandOption(Map<String, Object?> raw) {
return CommandOption(
type: CommandOptionType.parse(raw['type'] as int),
type: CommandOptionType(raw['type'] as int),
name: raw['name'] as String,
nameLocalizations: maybeParse(
raw['name_localizations'],
Expand All @@ -86,7 +86,7 @@ abstract class ApplicationCommandManager extends Manager<ApplicationCommand> {
isRequired: raw['required'] as bool?,
choices: maybeParseMany(raw['choices'], parseOptionChoice),
options: maybeParseMany(raw['options'], parseApplicationCommandOption),
channelTypes: maybeParseMany(raw['channel_types'], ChannelType.parse),
channelTypes: maybeParseMany(raw['channel_types'], ChannelType.new),
minValue: raw['min_value'] as num?,
maxValue: raw['max_value'] as num?,
minLength: raw['min_length'] as int?,
Expand Down Expand Up @@ -234,7 +234,7 @@ class GuildApplicationCommandManager extends ApplicationCommandManager {
CommandPermission parseCommandPermission(Map<String, Object?> raw) {
return CommandPermission(
id: Snowflake.parse(raw['id']!),
type: CommandPermissionType.parse(raw['type'] as int),
type: CommandPermissionType(raw['type'] as int),
hasPermission: raw['permission'] as bool,
);
}
Expand Down
8 changes: 4 additions & 4 deletions lib/src/http/managers/application_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class ApplicationManager {
raw['integration_types_config'],
(Map<String, Object?> config) => {
for (final MapEntry(:key, :value) in config.entries)
ApplicationIntegrationType.parse(int.parse(key)): parseApplicationIntegrationTypeConfiguration(value as Map<String, Object?>)
ApplicationIntegrationType(int.parse(key)): parseApplicationIntegrationTypeConfiguration(value as Map<String, Object?>)
},
),
roleConnectionsVerificationUrl: maybeParse(raw['role_connections_verification_url'], Uri.parse),
Expand All @@ -87,7 +87,7 @@ class ApplicationManager {
/// Parse a [TeamMember] from [raw].
TeamMember parseTeamMember(Map<String, Object?> raw) {
return TeamMember(
membershipState: TeamMembershipState.parse(raw['membership_state'] as int),
membershipState: TeamMembershipState(raw['membership_state'] as int),
teamId: Snowflake.parse(raw['team_id']!),
user: PartialUser(id: Snowflake.parse((raw['user'] as Map<String, Object?>)['id']!), manager: client.users),
role: TeamMemberRole.parse(raw['role'] as String),
Expand All @@ -112,7 +112,7 @@ class ApplicationManager {
/// Parse a [ApplicationRoleConnectionMetadata] from [raw].
ApplicationRoleConnectionMetadata parseApplicationRoleConnectionMetadata(Map<String, Object?> raw) {
return ApplicationRoleConnectionMetadata(
type: ConnectionMetadataType.parse(raw['type'] as int),
type: ConnectionMetadataType(raw['type'] as int),
key: raw['key'] as String,
name: raw['name'] as String,
localizedNames: maybeParse(
Expand All @@ -132,7 +132,7 @@ class ApplicationManager {
return Sku(
manager: this,
id: Snowflake.parse(raw['id']!),
type: SkuType.parse(raw['type'] as int),
type: SkuType(raw['type'] as int),
applicationId: Snowflake.parse(raw['application_id']!),
name: raw['name'] as String,
slug: raw['slug'] as String,
Expand Down
4 changes: 2 additions & 2 deletions lib/src/http/managers/audit_log_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class AuditLogManager extends ReadOnlyManager<AuditLogEntry> {
targetId: maybeParse(raw['target_id'], Snowflake.parse),
changes: maybeParseMany(raw['changes'], parseAuditLogChange),
userId: maybeParse(raw['user_id'], Snowflake.parse),
actionType: AuditLogEvent.parse(raw['action_type'] as int),
actionType: AuditLogEvent(raw['action_type'] as int),
options: maybeParse(raw['options'], parseAuditLogEntryInfo),
reason: raw['reason'] as String?,
);
Expand Down Expand Up @@ -53,7 +53,7 @@ class AuditLogManager extends ReadOnlyManager<AuditLogEntry> {
membersRemoved: raw['members_removed'] as String?,
messageId: maybeParse(raw['message_id'], Snowflake.parse),
roleName: raw['role_name'] as String?,
overwriteType: maybeParse(raw['type'], (String raw) => PermissionOverwriteType.parse(int.parse(raw))),
overwriteType: maybeParse(raw['type'], (String raw) => PermissionOverwriteType(int.parse(raw))),
integrationType: raw['integration_type'] as String?,
);
}
Expand Down
8 changes: 4 additions & 4 deletions lib/src/http/managers/auto_moderation_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ class AutoModerationManager extends Manager<AutoModerationRule> {
guildId: Snowflake.parse(raw['guild_id']!),
name: raw['name'] as String,
creatorId: Snowflake.parse(raw['creator_id']!),
eventType: AutoModerationEventType.parse(raw['event_type'] as int),
triggerType: TriggerType.parse(raw['trigger_type'] as int),
eventType: AutoModerationEventType(raw['event_type'] as int),
triggerType: TriggerType(raw['trigger_type'] as int),
metadata: parseTriggerMetadata(raw['trigger_metadata'] as Map<String, Object?>),
actions: parseMany(raw['actions'] as List<Object?>, parseAutoModerationAction),
isEnabled: raw['enabled'] as bool,
Expand All @@ -40,7 +40,7 @@ class AutoModerationManager extends Manager<AutoModerationRule> {
return TriggerMetadata(
keywordFilter: maybeParseMany(raw['keyword_filter']),
regexPatterns: maybeParseMany(raw['regex_patterns']),
presets: maybeParseMany(raw['presets'], KeywordPresetType.parse),
presets: maybeParseMany(raw['presets'], KeywordPresetType.new),
allowList: maybeParseMany(raw['allow_list']),
mentionTotalLimit: raw['mention_total_limit'] as int?,
isMentionRaidProtectionEnabled: raw['mention_raid_protection_enabled'] as bool?,
Expand All @@ -50,7 +50,7 @@ class AutoModerationManager extends Manager<AutoModerationRule> {
/// Parse a [AutoModerationAction] from [raw].
AutoModerationAction parseAutoModerationAction(Map<String, Object?> raw) {
return AutoModerationAction(
type: ActionType.parse(raw['type'] as int),
type: ActionType(raw['type'] as int),
metadata: maybeParse(raw['metadata'], parseActionMetadata),
);
}
Expand Down
16 changes: 8 additions & 8 deletions lib/src/http/managers/channel_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class ChannelManager extends ReadOnlyManager<Channel> {

@override
Channel parse(Map<String, Object?> raw, {Snowflake? guildId}) {
final type = ChannelType.parse(raw['type'] as int);
final type = ChannelType(raw['type'] as int);

final parsers = {
ChannelType.guildText: parseGuildTextChannel,
Expand Down Expand Up @@ -139,7 +139,7 @@ class ChannelManager extends ReadOnlyManager<Channel> {
rateLimitPerUser: maybeParse<Duration?, int>(raw['rate_limit_per_user'], (value) => value == 0 ? null : Duration(seconds: value)),
rtcRegion: raw['rtc_region'] as String?,
userLimit: raw['user_limit'] == 0 ? null : raw['user_limit'] as int?,
videoQualityMode: maybeParse(raw['video_quality_mode'], VideoQualityMode.parse) ?? VideoQualityMode.auto,
videoQualityMode: maybeParse(raw['video_quality_mode'], VideoQualityMode.new) ?? VideoQualityMode.auto,
);
}

Expand Down Expand Up @@ -305,7 +305,7 @@ class ChannelManager extends ReadOnlyManager<Channel> {
rateLimitPerUser: maybeParse<Duration?, int>(raw['rate_limit_per_user'], (value) => value == 0 ? null : Duration(seconds: value)),
rtcRegion: raw['rtc_region'] as String?,
userLimit: raw['user_limit'] == 0 ? null : raw['user_limit'] as int?,
videoQualityMode: maybeParse(raw['video_quality_mode'], VideoQualityMode.parse) ?? VideoQualityMode.auto,
videoQualityMode: maybeParse(raw['video_quality_mode'], VideoQualityMode.new) ?? VideoQualityMode.auto,
);
}

Expand All @@ -324,15 +324,15 @@ class ChannelManager extends ReadOnlyManager<Channel> {
return ForumChannel(
id: Snowflake.parse(raw['id']!),
manager: this,
defaultLayout: maybeParse(raw['default_forum_layout'], ForumLayout.parse),
defaultLayout: maybeParse(raw['default_forum_layout'], ForumLayout.new),
topic: raw['topic'] as String?,
rateLimitPerUser: maybeParse<Duration?, int>(raw['rate_limit_per_user'], (value) => value == 0 ? null : Duration(seconds: value)),
lastThreadId: maybeParse(raw['last_message_id'], Snowflake.parse),
lastPinTimestamp: maybeParse(raw['last_pin_timestamp'], DateTime.parse),
flags: ChannelFlags(raw['flags'] as int),
availableTags: parseMany(raw['available_tags'] as List, parseForumTag),
defaultReaction: maybeParse(raw['default_reaction_emoji'], parseDefaultReaction),
defaultSortOrder: maybeParse(raw['default_sort_order'], ForumSort.parse),
defaultSortOrder: maybeParse(raw['default_sort_order'], ForumSort.new),
// Discord doesn't seem to include this field if the default 3 day expiration is used (3 days = 4320 minutes)
defaultAutoArchiveDuration: Duration(minutes: raw['default_auto_archive_duration'] as int? ?? 4320),
defaultThreadRateLimitPerUser:
Expand All @@ -359,7 +359,7 @@ class ChannelManager extends ReadOnlyManager<Channel> {
flags: ChannelFlags(raw['flags'] as int),
availableTags: parseMany(raw['available_tags'] as List, parseForumTag),
defaultReaction: maybeParse(raw['default_reaction_emoji'], parseDefaultReaction),
defaultSortOrder: maybeParse(raw['default_sort_order'], ForumSort.parse),
defaultSortOrder: maybeParse(raw['default_sort_order'], ForumSort.new),
// Discord doesn't seem to include this field if the default 3 day expiration is used (3 days = 4320 minutes)
defaultAutoArchiveDuration: Duration(minutes: raw['default_auto_archive_duration'] as int? ?? 4320),
defaultThreadRateLimitPerUser:
Expand All @@ -376,7 +376,7 @@ class ChannelManager extends ReadOnlyManager<Channel> {
PermissionOverwrite parsePermissionOverwrite(Map<String, Object?> raw) {
return PermissionOverwrite(
id: Snowflake.parse(raw['id']!),
type: PermissionOverwriteType.parse(raw['type'] as int),
type: PermissionOverwriteType(raw['type'] as int),
allow: Permissions(int.parse(raw['allow'] as String)),
deny: Permissions(int.parse(raw['deny'] as String)),
);
Expand Down Expand Up @@ -436,7 +436,7 @@ class ChannelManager extends ReadOnlyManager<Channel> {
guildId: Snowflake.parse(raw['guild_id']!),
channelId: Snowflake.parse(raw['channel_id']!),
topic: raw['topic'] as String,
privacyLevel: PrivacyLevel.parse(raw['privacy_level'] as int),
privacyLevel: PrivacyLevel(raw['privacy_level'] as int),
scheduledEventId: maybeParse(raw['guild_scheduled_event_id'], Snowflake.parse),
);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/src/http/managers/entitlement_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class EntitlementManager extends ReadOnlyManager<Entitlement> {
userId: maybeParse(raw['user_id'], Snowflake.parse),
guildId: maybeParse(raw['guild_id'], Snowflake.parse),
applicationId: Snowflake.parse(raw['application_id']!),
type: EntitlementType.parse(raw['type'] as int),
type: EntitlementType(raw['type'] as int),
isConsumed: raw['consumed'] as bool? ?? false,
isDeleted: raw['deleted'] as bool? ?? false,
startsAt: maybeParse(raw['starts_at'], DateTime.parse),
Expand Down
8 changes: 4 additions & 4 deletions lib/src/http/managers/gateway_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ abstract class GatewayManager {
// No fields are validated server-side. Expect errors.
return Activity(
name: raw['name'] as String,
type: ActivityType.parse(raw['type'] as int),
type: ActivityType(raw['type'] as int),
url: tryParse(raw['url'], Uri.parse),
createdAt: tryParse(raw['created_at'], DateTime.fromMillisecondsSinceEpoch),
timestamps: tryParse(raw['timestamps'], parseActivityTimestamps),
Expand Down Expand Up @@ -103,9 +103,9 @@ abstract class GatewayManager {

ClientStatus parseClientStatus(Map<String, Object?> raw) {
return ClientStatus(
desktop: maybeParse(raw['desktop'], UserStatus.parse),
mobile: maybeParse(raw['mobile'], UserStatus.parse),
web: maybeParse(raw['web'], UserStatus.parse),
desktop: maybeParse(raw['desktop'], UserStatus.new),
mobile: maybeParse(raw['mobile'], UserStatus.new),
web: maybeParse(raw['web'], UserStatus.new),
);
}

Expand Down
16 changes: 8 additions & 8 deletions lib/src/http/managers/guild_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ class GuildManager extends Manager<Guild> {
afkTimeout: Duration(seconds: raw['afk_timeout'] as int),
isWidgetEnabled: raw['widget_enabled'] as bool? ?? false,
widgetChannelId: maybeParse(raw['widget_channel_id'], Snowflake.parse),
verificationLevel: VerificationLevel.parse(raw['verification_level'] as int),
defaultMessageNotificationLevel: MessageNotificationLevel.parse(raw['default_message_notifications'] as int),
explicitContentFilterLevel: ExplicitContentFilterLevel.parse(raw['explicit_content_filter'] as int),
verificationLevel: VerificationLevel(raw['verification_level'] as int),
defaultMessageNotificationLevel: MessageNotificationLevel(raw['default_message_notifications'] as int),
explicitContentFilterLevel: ExplicitContentFilterLevel(raw['explicit_content_filter'] as int),
roleList: parseMany(raw['roles'] as List, this[id].roles.parse),
features: parseGuildFeatures(raw['features'] as List),
mfaLevel: MfaLevel.parse(raw['mfa_level'] as int),
mfaLevel: MfaLevel(raw['mfa_level'] as int),
applicationId: maybeParse(raw['application_id'], Snowflake.parse),
systemChannelId: maybeParse(raw['system_channel_id'], Snowflake.parse),
systemChannelFlags: SystemChannelFlags(raw['system_channel_flags'] as int),
Expand All @@ -74,7 +74,7 @@ class GuildManager extends Manager<Guild> {
vanityUrlCode: raw['vanity_url_code'] as String?,
description: raw['description'] as String?,
bannerHash: raw['banner'] as String?,
premiumTier: PremiumTier.parse(raw['premium_tier'] as int),
premiumTier: PremiumTier(raw['premium_tier'] as int),
premiumSubscriptionCount: raw['premium_subscription_count'] as int?,
preferredLocale: Locale.parse(raw['preferred_locale'] as String),
publicUpdatesChannelId: maybeParse(raw['public_updates_channel_id'], Snowflake.parse),
Expand All @@ -83,7 +83,7 @@ class GuildManager extends Manager<Guild> {
approximateMemberCount: raw['approximate_member_count'] as int?,
approximatePresenceCount: raw['approximate_presence_count'] as int?,
welcomeScreen: maybeParse(raw['welcome_screen'], parseWelcomeScreen),
nsfwLevel: NsfwLevel.parse(raw['nsfw_level'] as int),
nsfwLevel: NsfwLevel(raw['nsfw_level'] as int),
hasPremiumProgressBarEnabled: raw['premium_progress_bar_enabled'] as bool,
emojiList: parseMany(raw['emojis'] as List, this[id].emojis.parse),
stickerList: parseMany(raw['stickers'] as List? ?? [], this[id].stickers.parse),
Expand Down Expand Up @@ -263,7 +263,7 @@ class GuildManager extends Manager<Guild> {
OnboardingPrompt parseOnboardingPrompt(Map<String, Object?> raw, {Snowflake? guildId}) {
return OnboardingPrompt(
id: Snowflake.parse(raw['id']!),
type: OnboardingPromptType.parse(raw['type'] as int),
type: OnboardingPromptType(raw['type'] as int),
options: parseMany(raw['options'] as List, (Map<String, Object?> raw) => parseOnboardingPromptOption(raw, guildId: guildId)),
title: raw['title'] as String,
isSingleSelect: raw['single_select'] as bool,
Expand Down Expand Up @@ -534,7 +534,7 @@ class GuildManager extends Manager<Guild> {
);

final response = await client.httpHandler.executeSafe(request);
return MfaLevel.parse((response.jsonBody as Map<String, Object?>)['level'] as int);
return MfaLevel((response.jsonBody as Map<String, Object?>)['level'] as int);
}

/// Fetch the prune count in a guild.
Expand Down
2 changes: 1 addition & 1 deletion lib/src/http/managers/integration_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class IntegrationManager extends ReadOnlyManager<Integration> {
isSyncing: raw['syncing'] as bool?,
roleId: maybeParse(raw['role_id'], Snowflake.parse),
enableEmoticons: raw['enable_emoticons'] as bool?,
expireBehavior: maybeParse(raw['expire_behavior'], IntegrationExpireBehavior.parse),
expireBehavior: maybeParse(raw['expire_behavior'], IntegrationExpireBehavior.new),
expireGracePeriod: maybeParse(raw['expire_grace_period'], (int value) => Duration(days: value)),
user: maybeParse(raw['user'], client.users.parse),
account: parseIntegrationAccount(raw['account'] as Map<String, Object?>),
Expand Down
Loading

0 comments on commit 672cd3d

Please sign in to comment.