diff --git a/lib/api/common/activity.dart b/lib/api/common/activity.dart index 51b17ccc..5fb32013 100644 --- a/lib/api/common/activity.dart +++ b/lib/api/common/activity.dart @@ -24,7 +24,8 @@ final class Activity { factory Activity.fromJson(Map json) { return Activity( name: json['name'], - type: ActivityType.values.firstWhere((element) => element.value == json['type'], + type: ActivityType.values.firstWhere( + (element) => element.value == json['type'], orElse: () => ActivityType.unknown), url: json['url'], createdAt: DateTime.fromMillisecondsSinceEpoch(json['created_at']), @@ -33,6 +34,8 @@ final class Activity { emoji: Helper.createOrNull( field: json['emoji'], fn: () => ActivityEmoji( - name: json['name'], id: json['id'], animated: json['animated'] ?? false))); + name: json['name'], + id: json['id'], + animated: json['animated'] ?? false))); } } diff --git a/lib/api/common/activity_emoji.dart b/lib/api/common/activity_emoji.dart index 96e245ff..73dbba04 100644 --- a/lib/api/common/activity_emoji.dart +++ b/lib/api/common/activity_emoji.dart @@ -8,4 +8,4 @@ final class ActivityEmoji { required this.id, required this.animated, }); -} \ No newline at end of file +} diff --git a/lib/api/common/bot.dart b/lib/api/common/bot.dart index c1cc777f..2286c5ec 100644 --- a/lib/api/common/bot.dart +++ b/lib/api/common/bot.dart @@ -33,21 +33,22 @@ final class Bot { }); factory Bot.fromJson(Map json) => Bot._( - id: Snowflake(json['user']['id']), - discriminator: json['user']['discriminator'], - version: json['v'], - username: json['user']['username'], - hasEnabledMfa: json['user']['mfa_enabled'], - globalName: json['user']['global_name'], - flags: json['user']['flags'], - avatar: json['user']['avatar'], - sessionType: json['session_type'], - privateChannels: json['private_channels'], - presences: json['presences'], - guildIds: List.from(json['guilds'].map((element) => element['id'])), - application: PartialApplication( - id: json['application']['id'], - flags: json['application']['flags'], - ), - ); + id: Snowflake(json['user']['id']), + discriminator: json['user']['discriminator'], + version: json['v'], + username: json['user']['username'], + hasEnabledMfa: json['user']['mfa_enabled'], + globalName: json['user']['global_name'], + flags: json['user']['flags'], + avatar: json['user']['avatar'], + sessionType: json['session_type'], + privateChannels: json['private_channels'], + presences: json['presences'], + guildIds: + List.from(json['guilds'].map((element) => element['id'])), + application: PartialApplication( + id: json['application']['id'], + flags: json['application']['flags'], + ), + ); } diff --git a/lib/api/common/channel_methods.dart b/lib/api/common/channel_methods.dart index b4bfbc50..00709346 100644 --- a/lib/api/common/channel_methods.dart +++ b/lib/api/common/channel_methods.dart @@ -62,7 +62,8 @@ final class ChannelMethods { ); } - Future setDefaultAutoArchiveDuration(int defaultAutoArchiveDuration, String? reason) async { + Future setDefaultAutoArchiveDuration( + int defaultAutoArchiveDuration, String? reason) async { await dataStoreChannel.updateChannel( id: id, reason: reason, @@ -70,7 +71,8 @@ final class ChannelMethods { ); } - Future setDefaultThreadRateLimitPerUser(int value, String? reason) async { + Future setDefaultThreadRateLimitPerUser( + int value, String? reason) async { await dataStoreChannel.updateChannel( id: id, reason: reason, @@ -110,8 +112,14 @@ final class ChannelMethods { ); } - Future send({ Snowflake? guildId, String? content, List? embeds, Poll? poll, List? components}) async { - await dataStoreChannel.createMessage(guildId, id, content, embeds, poll, components); + Future send( + {Snowflake? guildId, + String? content, + List? embeds, + Poll? poll, + List? components}) async { + await dataStoreChannel.createMessage( + guildId, id, content, embeds, poll, components); } Future delete(String? reason) async { diff --git a/lib/api/common/channel_properties.dart b/lib/api/common/channel_properties.dart index 87fb8c2e..d5877b12 100644 --- a/lib/api/common/channel_properties.dart +++ b/lib/api/common/channel_properties.dart @@ -84,55 +84,59 @@ final class ChannelProperties { final permissionOverwrites = await Helper.createOrNullAsync( field: element['permission_overwrites'], fn: () async => Future.wait( - List.from(element['permission_overwrites']) - .map((json) async => - marshaller.serializers.channelPermissionOverwrite.serialize(json)) - .toList(), - )); + List.from(element['permission_overwrites']) + .map((json) async => marshaller + .serializers.channelPermissionOverwrite + .serialize(json)) + .toList(), + )); final recipients = await Helper.createOrNullAsync( field: element['recipients'], fn: () async => Future.wait( - List.from(element['recipients']) - .map((json) async => marshaller.serializers.user.serialize(json)) - .toList(), - )); + List.from(element['recipients']) + .map((json) async => + marshaller.serializers.user.serialize(json)) + .toList(), + )); return ChannelProperties( - id: Snowflake(element['id']), - type: findInEnum(ChannelType.values, element['type']), - name: element['name'], - description: element['description'], - serverId: Helper.createOrNull( - field: element['server_id'], fn: () => Snowflake(element['server_id'])), - categoryId: Helper.createOrNull( - field: element['parent_id'], fn: () => Snowflake(element['parent_id'])), - position: element['position'], - nsfw: element['nsfw'] ?? false, - lastMessageId: Helper.createOrNull( - field: element['last_message_id'], fn: () => Snowflake(element['last_message_id'])), - bitrate: element['bitrate'], - userLimit: element['user_limit'], - rateLimitPerUser: element['rate_limit_per_user'], - recipients: recipients ?? [], - icon: element['icon'], - ownerId: element['owner_id'], - applicationId: element['application_id'], - lastPinTimestamp: element['last_pin_timestamp'], - rtcRegion: element['rtc_region'], - videoQualityMode: element['video_quality_mode'], - messageCount: element['message_count'], - memberCount: element['member_count'], - defaultAutoArchiveDuration: element['default_auto_archive_duration'], - permissions: permissionOverwrites, - flags: element['flags'], - totalMessageSent: element['total_message_sent'], - available: element['available'], - appliedTags: element['applied_tags'] ?? [], - defaultReactions: element['default_reactions'], - defaultSortOrder: element['default_sort_order'], - defaultForumLayout: element['default_forum_layout'], - threads: ThreadsManager({}) - ); + id: Snowflake(element['id']), + type: findInEnum(ChannelType.values, element['type']), + name: element['name'], + description: element['description'], + serverId: Helper.createOrNull( + field: element['server_id'], + fn: () => Snowflake(element['server_id'])), + categoryId: Helper.createOrNull( + field: element['parent_id'], + fn: () => Snowflake(element['parent_id'])), + position: element['position'], + nsfw: element['nsfw'] ?? false, + lastMessageId: Helper.createOrNull( + field: element['last_message_id'], + fn: () => Snowflake(element['last_message_id'])), + bitrate: element['bitrate'], + userLimit: element['user_limit'], + rateLimitPerUser: element['rate_limit_per_user'], + recipients: recipients ?? [], + icon: element['icon'], + ownerId: element['owner_id'], + applicationId: element['application_id'], + lastPinTimestamp: element['last_pin_timestamp'], + rtcRegion: element['rtc_region'], + videoQualityMode: element['video_quality_mode'], + messageCount: element['message_count'], + memberCount: element['member_count'], + defaultAutoArchiveDuration: element['default_auto_archive_duration'], + permissions: permissionOverwrites, + flags: element['flags'], + totalMessageSent: element['total_message_sent'], + available: element['available'], + appliedTags: element['applied_tags'] ?? [], + defaultReactions: element['default_reactions'], + defaultSortOrder: element['default_sort_order'], + defaultForumLayout: element['default_forum_layout'], + threads: ThreadsManager({})); } } diff --git a/lib/api/common/color.dart b/lib/api/common/color.dart index a67c43ef..a2fe5de2 100644 --- a/lib/api/common/color.dart +++ b/lib/api/common/color.dart @@ -214,10 +214,10 @@ final class Color { final String _color; Color(this._color); - int toInt () => int.parse(_color.replaceAll('#', ''), radix: 16); + int toInt() => int.parse(_color.replaceAll('#', ''), radix: 16); @override - String toString () => _color; + String toString() => _color; factory Color.of(int color) { final hex = color.toRadixString(16); diff --git a/lib/api/common/commands/builder/command_builder.dart b/lib/api/common/commands/builder/command_builder.dart index 114eb335..7846f246 100644 --- a/lib/api/common/commands/builder/command_builder.dart +++ b/lib/api/common/commands/builder/command_builder.dart @@ -37,21 +37,24 @@ final class CommandBuilder { final firstArg = fn.toString().split('(')[1].split(')')[0].split(' ')[0]; if (!firstArg.contains('CommandContext')) { - throw Exception('The first argument of the handler function must be CommandContext'); + throw Exception( + 'The first argument of the handler function must be CommandContext'); } _handle = fn; return this; } - CommandBuilder addSubCommand(SubCommandBuilder Function(SubCommandBuilder) command) { + CommandBuilder addSubCommand( + SubCommandBuilder Function(SubCommandBuilder) command) { final builder = SubCommandBuilder(); command(builder); _subCommands.add(builder); return this; } - CommandBuilder createGroup(CommandGroupBuilder Function(CommandGroupBuilder) group) { + CommandBuilder createGroup( + CommandGroupBuilder Function(CommandGroupBuilder) group) { final builder = CommandGroupBuilder(); group(builder); _groups.add(builder); @@ -68,14 +71,15 @@ final class CommandBuilder { return { 'name': _name, 'description': _description, - if (_subCommands.isEmpty && _groups.isEmpty) 'type': CommandType.subCommand.value, + if (_subCommands.isEmpty && _groups.isEmpty) + 'type': CommandType.subCommand.value, 'options': options, }; } List<(String, Function handler)> reduceHandlers() { if (_subCommands.isEmpty && _groups.isEmpty) { - return [('$_name', _handle!)]; + return [('$_name', _handle!)]; } final List<(String, Function handler)> handlers = []; @@ -86,11 +90,11 @@ final class CommandBuilder { for (final group in _groups) { for (final subCommand in group.commands) { - handlers.add(('$_name.${group.name}.${subCommand.name}', subCommand.handle!)); + handlers.add( + ('$_name.${group.name}.${subCommand.name}', subCommand.handle!)); } } return handlers; } } - diff --git a/lib/api/common/commands/builder/command_declaration_builder.dart b/lib/api/common/commands/builder/command_declaration_builder.dart index 18f99d6c..894b9922 100644 --- a/lib/api/common/commands/builder/command_declaration_builder.dart +++ b/lib/api/common/commands/builder/command_declaration_builder.dart @@ -108,7 +108,8 @@ final class CommandDeclarationBuilder implements CommandBuilder { for (final subCommand in subCommands) { if (subCommand.handle case null) { - throw MissingMethodException('Command "$commandName.${subCommand.name}" has no handler'); + throw MissingMethodException( + 'Command "$commandName.${subCommand.name}" has no handler'); } handlers.add(('$name.${subCommand.name}', subCommand.handle!)); diff --git a/lib/api/common/commands/builder/command_definition_builder.dart b/lib/api/common/commands/builder/command_definition_builder.dart index beda20d0..99424ef2 100644 --- a/lib/api/common/commands/builder/command_definition_builder.dart +++ b/lib/api/common/commands/builder/command_definition_builder.dart @@ -17,7 +17,8 @@ final class CommandDefinitionBuilder implements CommandBuilder { final Map _commandMapper = {}; final CommandDeclarationBuilder command = CommandDeclarationBuilder(); - String _extractDefaultValue(String commandKey, String key, Map payload) { + String _extractDefaultValue( + String commandKey, String key, Map payload) { final Map? elements = payload[key]; if (elements == null) { throw Exception('Missing "$key" key under $commandKey'); @@ -27,17 +28,20 @@ final class CommandDefinitionBuilder implements CommandBuilder { return value; } - throw Exception('Missing "$key.$_defaultIdentifier" key under $commandKey struct'); + throw Exception( + 'Missing "$key.$_defaultIdentifier" key under $commandKey struct'); } - Map _extractTranslations(String key, Map payload) { + Map _extractTranslations( + String key, Map payload) { final Map? elements = payload[key]; if (elements == null) { throw Exception('Missing "$key" key'); } - return elements.entries.whereNot((element) => element.key == _defaultIdentifier).fold({}, - (acc, element) { + return elements.entries + .whereNot((element) => element.key == _defaultIdentifier) + .fold({}, (acc, element) { final lang = Lang.values.firstWhere((lang) => lang.uid == element.key); return {...acc, lang: element.value}; }); @@ -47,16 +51,19 @@ final class CommandDefinitionBuilder implements CommandBuilder { final Map groupList = content['groups'] ?? {}; for (final element in groupList.entries) { - final String defaultName = _extractDefaultValue(element.key, 'name', element.value); + final String defaultName = + _extractDefaultValue(element.key, 'name', element.value); final String defaultDescription = _extractDefaultValue(element.key, 'description', element.value); final nameTranslations = _extractTranslations('name', element.value); - final descriptionTranslations = _extractTranslations('description', element.value); + final descriptionTranslations = + _extractTranslations('description', element.value); command.createGroup((group) { return group - ..setName(defaultName, translation: Translation({'name': nameTranslations})) + ..setName(defaultName, + translation: Translation({'name': nameTranslations})) ..setDescription(defaultDescription, translation: Translation({'name': descriptionTranslations})); }); @@ -64,50 +71,56 @@ final class CommandDefinitionBuilder implements CommandBuilder { } List _declareOptions(MapEntry element) { - final options = List>.from(element.value['options'] ?? []); + final options = + List>.from(element.value['options'] ?? []); return options.fold([], (acc, Map element) { final String name = _extractDefaultValue('option', 'name', element); - final String description = _extractDefaultValue('option', 'description', element); + final String description = + _extractDefaultValue('option', 'description', element); final bool required = element['required'] ?? false; final option = switch (element['type']) { - final String value when value == 'string' => - Option.string(name: name, description: description, required: required), - final String value when value == 'integer' => - Option.integer(name: name, description: description, required: required), - final String value when value == 'double' => - Option.double(name: name, description: description, required: required), - final String value when value == 'string' => - Option.boolean(name: name, description: description, required: required), + final String value when value == 'string' => Option.string( + name: name, description: description, required: required), + final String value when value == 'integer' => Option.integer( + name: name, description: description, required: required), + final String value when value == 'double' => Option.double( + name: name, description: description, required: required), + final String value when value == 'string' => Option.boolean( + name: name, description: description, required: required), final String value when value == 'user' => Option.user(name: name, description: description, required: required), - final String value when value == 'channel' => - Option.channel(name: name, description: description, required: required), + final String value when value == 'channel' => Option.channel( + name: name, description: description, required: required), final String value when value == 'role' => Option.role(name: name, description: description, required: required), - final String value when value == 'mention' => - Option.mentionable(name: name, description: description, required: required), + final String value when value == 'mention' => Option.mentionable( + name: name, description: description, required: required), final String value when value == 'choice.string' => ChoiceOption.string( name: name, description: description, required: required, choices: List.from(element['choices'] ?? []) - .map((element) => Choice(element['name'], element['value'])) - .toList()), - final String value when value == 'choice.integer' => ChoiceOption.integer( - name: name, - description: description, - required: required, - choices: List.from(element['choices'] ?? []) - .map((element) => Choice(element['name'], int.parse(element['value']))) + .map((element) => + Choice(element['name'], element['value'])) .toList()), + final String value when value == 'choice.integer' => + ChoiceOption.integer( + name: name, + description: description, + required: required, + choices: List.from(element['choices'] ?? []) + .map((element) => + Choice(element['name'], int.parse(element['value']))) + .toList()), final String value when value == 'choice.double' => ChoiceOption.double( name: name, description: description, required: required, choices: List.from(element['choices'] ?? []) - .map((element) => Choice(element['name'], double.parse(element['value']))) + .map((element) => + Choice(element['name'], double.parse(element['value']))) .toList()), _ => throw Exception('Unknown option type') }; @@ -121,20 +134,25 @@ final class CommandDefinitionBuilder implements CommandBuilder { for (final element in commandList.entries) { if (element.key.contains('.')) { - final String defaultName = _extractDefaultValue(element.key, 'name', element.value); + final String defaultName = + _extractDefaultValue(element.key, 'name', element.value); final String defaultDescription = _extractDefaultValue(element.key, 'description', element.value); final nameTranslations = _extractTranslations('name', element.value); - final descriptionTranslations = _extractTranslations('description', element.value); + final descriptionTranslations = + _extractTranslations('description', element.value); if (element.value['group'] case final String group) { - final currentGroup = command.groups.firstWhere((element) => element.name == group) + final currentGroup = command.groups + .firstWhere((element) => element.name == group) ..addSubCommand((command) { command - ..setName(defaultName, translation: Translation({'name': nameTranslations})) + ..setName(defaultName, + translation: Translation({'name': nameTranslations})) ..setDescription(defaultDescription, - translation: Translation({'description': descriptionTranslations})); + translation: + Translation({'description': descriptionTranslations})); command.options.addAll(_declareOptions(element)); }); @@ -142,19 +160,23 @@ final class CommandDefinitionBuilder implements CommandBuilder { final int currentGroupIndex = command.groups.indexOf(currentGroup); final int currentSubCommandIndex = currentGroup.commands.indexOf(currentGroup.commands.last); - _commandMapper[element.key] = - () => command.groups[currentGroupIndex].commands[currentSubCommandIndex]; + _commandMapper[element.key] = () => command + .groups[currentGroupIndex].commands[currentSubCommandIndex]; } else { command.addSubCommand((command) { command - ..setName(defaultName, translation: Translation({'name': nameTranslations})) + ..setName(defaultName, + translation: Translation({'name': nameTranslations})) ..setDescription(defaultDescription, - translation: Translation({'description': descriptionTranslations})); + translation: + Translation({'description': descriptionTranslations})); command.options.addAll(_declareOptions(element)); }); - final currentSubCommandIndex = command.subCommands.indexOf(command.subCommands.last); - _commandMapper[element.key] = () => command.subCommands[currentSubCommandIndex]; + final currentSubCommandIndex = + command.subCommands.indexOf(command.subCommands.last); + _commandMapper[element.key] = + () => command.subCommands[currentSubCommandIndex]; } } } @@ -165,17 +187,21 @@ final class CommandDefinitionBuilder implements CommandBuilder { for (final element in commandList.entries) { if (!element.key.contains('.')) { - final String defaultName = _extractDefaultValue(element.key, 'name', element.value); + final String defaultName = + _extractDefaultValue(element.key, 'name', element.value); final String defaultDescription = _extractDefaultValue(element.key, 'description', element.value); final nameTranslations = _extractTranslations('name', element.value); - final descriptionTranslations = _extractTranslations('description', element.value); + final descriptionTranslations = + _extractTranslations('description', element.value); command - ..setName(defaultName, translation: Translation({'name': nameTranslations})) + ..setName(defaultName, + translation: Translation({'name': nameTranslations})) ..setDescription(defaultDescription, - translation: Translation({'description': descriptionTranslations})); + translation: + Translation({'description': descriptionTranslations})); command.options.addAll(_declareOptions(element)); @@ -185,14 +211,16 @@ final class CommandDefinitionBuilder implements CommandBuilder { } CommandDefinitionBuilder context(String key, Function(T) fn) { - final command = _commandMapper.entries.firstWhere((element) => element.key == key); + final command = + _commandMapper.entries.firstWhere((element) => element.key == key); fn(command.value()); return this; } CommandDefinitionBuilder setHandler(String key, Function fn) { - final command = _commandMapper.entries.firstWhere((element) => element.key == key); + final command = + _commandMapper.entries.firstWhere((element) => element.key == key); switch (command.value()) { case final SubCommandBuilder command: @@ -207,8 +235,10 @@ final class CommandDefinitionBuilder implements CommandBuilder { CommandDefinitionBuilder using(File file) { final String stringContent = file.readAsStringSync(); final content = switch (file.path) { - final String path when path.contains('.json') => jsonDecode(stringContent), - final String path when path.contains('.yaml') => (loadYaml(stringContent) as YamlMap).toMap(), + final String path when path.contains('.json') => + jsonDecode(stringContent), + final String path when path.contains('.yaml') => + (loadYaml(stringContent) as YamlMap).toMap(), _ => throw Exception('File type not supported') }; diff --git a/lib/api/common/commands/command_declaration.dart b/lib/api/common/commands/command_declaration.dart index 41018850..d248a650 100644 --- a/lib/api/common/commands/command_declaration.dart +++ b/lib/api/common/commands/command_declaration.dart @@ -1,7 +1,8 @@ import 'package:mineral/api/common/commands/builder/command_declaration_builder.dart'; import 'package:mineral/api/common/commands/command_contract.dart'; -abstract interface class CommandDeclaration implements CommandContract{ +abstract interface class CommandDeclaration + implements CommandContract { @override CommandDeclarationBuilder build(); } diff --git a/lib/api/common/commands/command_definition.dart b/lib/api/common/commands/command_definition.dart index 12a262d8..595647b0 100644 --- a/lib/api/common/commands/command_definition.dart +++ b/lib/api/common/commands/command_definition.dart @@ -1,7 +1,8 @@ import 'package:mineral/api/common/commands/builder/command_definition_builder.dart'; import 'package:mineral/api/common/commands/command_contract.dart'; -abstract interface class CommandDefinition implements CommandContract{ +abstract interface class CommandDefinition + implements CommandContract { @override CommandDefinitionBuilder build(); } diff --git a/lib/api/common/components/buttons/button_builder.dart b/lib/api/common/components/buttons/button_builder.dart index 619728bd..3eba4c7d 100644 --- a/lib/api/common/components/buttons/button_builder.dart +++ b/lib/api/common/components/buttons/button_builder.dart @@ -20,10 +20,13 @@ final class ButtonBuilder { static LinkButtonBuilder link() => LinkButtonBuilder(); - static PremiumButtonBuilder premium(String skuId) => PremiumButtonBuilder(skuId); + static PremiumButtonBuilder premium(String skuId) => + PremiumButtonBuilder(skuId); } -final class BasicButtonBuilder with ButtonImpl implements ButtonBuilderContract { +final class BasicButtonBuilder + with ButtonImpl + implements ButtonBuilderContract { final ButtonType _type; final String _customId; @@ -56,7 +59,9 @@ final class PremiumButtonBuilder implements ButtonBuilderContract { } } -final class LinkButtonBuilder with ButtonImpl implements ButtonBuilderContract { +final class LinkButtonBuilder + with ButtonImpl + implements ButtonBuilderContract { final ButtonType _type = ButtonType.link; String? _url; diff --git a/lib/api/common/components/dialogs/dialog_element.dart b/lib/api/common/components/dialogs/dialog_element.dart index 0ddb7cc3..ed952567 100644 --- a/lib/api/common/components/dialogs/dialog_element.dart +++ b/lib/api/common/components/dialogs/dialog_element.dart @@ -6,7 +6,8 @@ abstract interface class DialogElement implements MessageComponent {} final class DialogElementBuilder { static DialogTextInput input(String customId) => DialogTextInput(customId); - static DialogParagraphInput paragraph(String customId) => DialogParagraphInput(customId); + static DialogParagraphInput paragraph(String customId) => + DialogParagraphInput(customId); } final class DialogTextInput with DialogElementImpl implements DialogElement { @@ -25,7 +26,9 @@ final class DialogTextInput with DialogElementImpl implements DialogElement { } } -final class DialogParagraphInput with DialogElementImpl implements DialogElement { +final class DialogParagraphInput + with DialogElementImpl + implements DialogElement { final String _customId; DialogParagraphInput(this._customId); diff --git a/lib/api/common/components/menus/select_menu_builder.dart b/lib/api/common/components/menus/select_menu_builder.dart index 8444161a..f68cc54b 100644 --- a/lib/api/common/components/menus/select_menu_builder.dart +++ b/lib/api/common/components/menus/select_menu_builder.dart @@ -5,16 +5,21 @@ import 'package:mineral/api/common/partial_emoji.dart'; import 'package:mineral/api/common/snowflake.dart'; import 'package:mineral/api/common/types/channel_type.dart'; -abstract interface class SelectMenuBuilderContract implements MessageComponent {} +abstract interface class SelectMenuBuilderContract + implements MessageComponent {} final class SelectMenuBuilder { - static SelectMenuTextBuilder text(String customId) => SelectMenuTextBuilder(customId); + static SelectMenuTextBuilder text(String customId) => + SelectMenuTextBuilder(customId); - static SelectMenuChannelBuilder channel(String customId) => SelectMenuChannelBuilder(customId); + static SelectMenuChannelBuilder channel(String customId) => + SelectMenuChannelBuilder(customId); - static SelectMenuUserBuilder user(String customId) => SelectMenuUserBuilder(customId); + static SelectMenuUserBuilder user(String customId) => + SelectMenuUserBuilder(customId); - static SelectMenuRoleBuilder role(String customId) => SelectMenuRoleBuilder(customId); + static SelectMenuRoleBuilder role(String customId) => + SelectMenuRoleBuilder(customId); static SelectMenuMentionableBuilder mentionable(String customId) => SelectMenuMentionableBuilder(customId); @@ -81,9 +86,13 @@ final class SelectMenuChannelBuilder ...super.toJson(), 'type': ComponentType.channelSelectMenu.value, 'custom_id': _customId, - 'channel_types': _channelTypes.isNotEmpty ? _channelTypes.map((e) => e.value).toList() : null, + 'channel_types': _channelTypes.isNotEmpty + ? _channelTypes.map((e) => e.value).toList() + : null, 'default_values': _defaultChannels.isNotEmpty - ? _defaultChannels.map((e) => {'id': e.value, 'type': 'channel'}).toList() + ? _defaultChannels + .map((e) => {'id': e.value, 'type': 'channel'}) + .toList() : null, }; } diff --git a/lib/api/common/components/menus/select_menu_option.dart b/lib/api/common/components/menus/select_menu_option.dart index aaebd22c..5dfa6d31 100644 --- a/lib/api/common/components/menus/select_menu_option.dart +++ b/lib/api/common/components/menus/select_menu_option.dart @@ -7,18 +7,24 @@ final class SelectMenuOption { final PartialEmoji? emoji; final bool? isDefault; - SelectMenuOption({required this.label, required this.value, this.description, this.emoji, this.isDefault = false}); + SelectMenuOption( + {required this.label, + required this.value, + this.description, + this.emoji, + this.isDefault = false}); Map toJson() { return { 'label': label, 'value': value, 'description': description, - if (emoji != null) 'emoji': { - 'name': emoji?.name, - 'id': emoji?.id, - 'animated': emoji?.animated, - }, + if (emoji != null) + 'emoji': { + 'name': emoji?.name, + 'id': emoji?.id, + 'animated': emoji?.animated, + }, 'default': isDefault, }; } diff --git a/lib/api/common/embed/message_embed_assets.dart b/lib/api/common/embed/message_embed_assets.dart index beafed65..dfae731a 100644 --- a/lib/api/common/embed/message_embed_assets.dart +++ b/lib/api/common/embed/message_embed_assets.dart @@ -35,15 +35,20 @@ final class MessageEmbedAssets { factory MessageEmbedAssets.fromJson(Map json) { return MessageEmbedAssets( image: Helper.createOrNull( - field: json['image'], fn: () => MessageEmbedImage.fromJson(json['image'])), + field: json['image'], + fn: () => MessageEmbedImage.fromJson(json['image'])), thumbnail: Helper.createOrNull( - field: json['thumbnail'], fn: () => MessageEmbedImage.fromJson(json['thumbnail'])), + field: json['thumbnail'], + fn: () => MessageEmbedImage.fromJson(json['thumbnail'])), video: Helper.createOrNull( - field: json['video'], fn: () => MessageEmbedImage.fromJson(json['video'])), + field: json['video'], + fn: () => MessageEmbedImage.fromJson(json['video'])), footer: Helper.createOrNull( - field: json['footer'], fn: () => MessageEmbedFooter.fromJson(json['footer'])), + field: json['footer'], + fn: () => MessageEmbedFooter.fromJson(json['footer'])), author: Helper.createOrNull( - field: json['author'], fn: () => MessageEmbedAuthor.fromJson(json['author'])), + field: json['author'], + fn: () => MessageEmbedAuthor.fromJson(json['author'])), color: json['color'], ); } diff --git a/lib/api/common/embed/message_embed_author.dart b/lib/api/common/embed/message_embed_author.dart index 82f8de72..7b94038b 100644 --- a/lib/api/common/embed/message_embed_author.dart +++ b/lib/api/common/embed/message_embed_author.dart @@ -7,8 +7,12 @@ final class MessageEmbedAuthor { final String? proxyIconUrl; MessageEmbedAuthor( - {required this.name, required this.url, required this.iconUrl, required this.proxyIconUrl}) { - expectOrThrow(name.length <= 256, message: 'Author name must be 256 or fewer in length'); + {required this.name, + required this.url, + required this.iconUrl, + required this.proxyIconUrl}) { + expectOrThrow(name.length <= 256, + message: 'Author name must be 256 or fewer in length'); } Object toJson() { diff --git a/lib/api/common/embed/message_embed_builder.dart b/lib/api/common/embed/message_embed_builder.dart index 3ed860d0..41c5eb8e 100644 --- a/lib/api/common/embed/message_embed_builder.dart +++ b/lib/api/common/embed/message_embed_builder.dart @@ -39,18 +39,25 @@ final class MessageEmbedBuilder { return this; } - MessageEmbedBuilder setFooter({required String text, String? iconUrl, String? proxyIconUrl}) { - footer = MessageEmbedFooter(text: text, iconUrl: iconUrl, proxyIconUrl: proxyIconUrl); + MessageEmbedBuilder setFooter( + {required String text, String? iconUrl, String? proxyIconUrl}) { + footer = MessageEmbedFooter( + text: text, iconUrl: iconUrl, proxyIconUrl: proxyIconUrl); return this; } MessageEmbedBuilder setAuthor( - {required String name, String? url, String? iconUrl, String? proxyIconUrl}) { - author = MessageEmbedAuthor(name: name, url: url, iconUrl: iconUrl, proxyIconUrl: proxyIconUrl); + {required String name, + String? url, + String? iconUrl, + String? proxyIconUrl}) { + author = MessageEmbedAuthor( + name: name, url: url, iconUrl: iconUrl, proxyIconUrl: proxyIconUrl); return this; } - MessageEmbedBuilder addField({required String name, required String value, bool inline = false}) { + MessageEmbedBuilder addField( + {required String name, required String value, bool inline = false}) { fields.add(MessageEmbedField(name: name, value: value)); return this; } @@ -60,19 +67,24 @@ final class MessageEmbedBuilder { return this; } - MessageEmbedBuilder setImage({required String url, String? proxyUrl, int? height, int? width}) { - image = MessageEmbedImage(url: url, proxyUrl: proxyUrl, height: height, width: width); + MessageEmbedBuilder setImage( + {required String url, String? proxyUrl, int? height, int? width}) { + image = MessageEmbedImage( + url: url, proxyUrl: proxyUrl, height: height, width: width); return this; } MessageEmbedBuilder setThumbnail( {required String url, String? proxyUrl, int? height, int? width}) { - image = MessageEmbedImage(url: url, proxyUrl: proxyUrl, height: height, width: width); + image = MessageEmbedImage( + url: url, proxyUrl: proxyUrl, height: height, width: width); return this; } - MessageEmbedBuilder setVideo({required String url, String? proxyUrl, int? height, int? width}) { - image = MessageEmbedImage(url: url, proxyUrl: proxyUrl, height: height, width: width); + MessageEmbedBuilder setVideo( + {required String url, String? proxyUrl, int? height, int? width}) { + image = MessageEmbedImage( + url: url, proxyUrl: proxyUrl, height: height, width: width); return this; } diff --git a/lib/api/common/embed/message_embed_field.dart b/lib/api/common/embed/message_embed_field.dart index 5491e901..490d6101 100644 --- a/lib/api/common/embed/message_embed_field.dart +++ b/lib/api/common/embed/message_embed_field.dart @@ -5,9 +5,12 @@ final class MessageEmbedField { final String value; final bool inline; - MessageEmbedField({required this.name, required this.value, this.inline = false}) { - expectOrThrow(name.length <= 256, message: 'Name must be 256 or fewer in length'); - expectOrThrow(value.length <= 1024, message: 'Value must be 1024 or fewer in length'); + MessageEmbedField( + {required this.name, required this.value, this.inline = false}) { + expectOrThrow(name.length <= 256, + message: 'Name must be 256 or fewer in length'); + expectOrThrow(value.length <= 1024, + message: 'Value must be 1024 or fewer in length'); } Object toJson() { diff --git a/lib/api/common/embed/message_embed_footer.dart b/lib/api/common/embed/message_embed_footer.dart index 3c6d33cb..7eed414f 100644 --- a/lib/api/common/embed/message_embed_footer.dart +++ b/lib/api/common/embed/message_embed_footer.dart @@ -6,8 +6,9 @@ final class MessageEmbedFooter { final String? proxyIconUrl; MessageEmbedFooter( - {required this.text, required this.iconUrl, required this.proxyIconUrl }) { - expectOrThrow(text.length <= 2048, message: 'Text must be 2048 or fewer in length'); + {required this.text, required this.iconUrl, required this.proxyIconUrl}) { + expectOrThrow(text.length <= 2048, + message: 'Text must be 2048 or fewer in length'); } Object toJson() { diff --git a/lib/api/common/image_asset.dart b/lib/api/common/image_asset.dart index be543ffa..68b5bb39 100644 --- a/lib/api/common/image_asset.dart +++ b/lib/api/common/image_asset.dart @@ -23,7 +23,7 @@ final class ImageAsset { String get url => '$_baseUrl/${_fragments.join('/')}/$hash.png'; - String makeUrl({ ImageExtension extension = ImageExtension.png, int? size }) { + String makeUrl({ImageExtension extension = ImageExtension.png, int? size}) { if (size case int() when size < 16 || size > 4096) { throw ArgumentError('Size must be between 16 and 4096'); } diff --git a/lib/api/common/lang.dart b/lib/api/common/lang.dart index 807f7b18..cfb519b1 100644 --- a/lib/api/common/lang.dart +++ b/lib/api/common/lang.dart @@ -2,7 +2,7 @@ enum Lang { id('id', 'Indonesian'), da('da', 'Danish'), de('de', 'German'), - enGB('en-GB', 'UK English'), + enGB('en-GB', 'UK English'), enUS('en-US', 'US English'), esES('es-ES', 'Spanish'), fr('fr', 'French'), @@ -13,7 +13,7 @@ enum Lang { nl('nl', 'Dutch'), no('no', 'Norwegian'), pl('pl', 'Polish'), - pt('pt-BR', 'Portuguese'), + pt('pt-BR', 'Portuguese'), ro('ro', 'Romanian'), fi('fi', 'Finnish'), svSE('sv-SE', 'Swedish'), @@ -28,7 +28,7 @@ enum Lang { th('th', 'Thai'), zh('zh-CN', 'Chinese'), ja('ja', 'Japanese'), - zhTW('zh-TW', 'Chinese'), + zhTW('zh-TW', 'Chinese'), ko('ko', 'Korean'); final String uid; diff --git a/lib/api/common/message_properties.dart b/lib/api/common/message_properties.dart index 47be0a4c..085a8efb 100644 --- a/lib/api/common/message_properties.dart +++ b/lib/api/common/message_properties.dart @@ -35,7 +35,8 @@ final class MessageProperties { embeds: embeds, createdAt: DateTime.parse(json['timestamp']), updatedAt: Helper.createOrNull( - field: json['edited_timestamp'], fn: () => DateTime.parse(json['edited_timestamp'])), + field: json['edited_timestamp'], + fn: () => DateTime.parse(json['edited_timestamp'])), ); } } diff --git a/lib/api/common/partial_emoji.dart b/lib/api/common/partial_emoji.dart index 83555b1b..c8d30ddc 100644 --- a/lib/api/common/partial_emoji.dart +++ b/lib/api/common/partial_emoji.dart @@ -8,6 +8,8 @@ class PartialEmoji { const PartialEmoji(this.id, this.name, this.animated); - factory PartialEmoji.fromUnicode(String value) => PartialEmoji(null, value, false); - factory PartialEmoji.fromEmoji(Emoji emoji) => PartialEmoji(emoji.id, emoji.name, emoji.animated); + factory PartialEmoji.fromUnicode(String value) => + PartialEmoji(null, value, false); + factory PartialEmoji.fromEmoji(Emoji emoji) => + PartialEmoji(emoji.id, emoji.name, emoji.animated); } diff --git a/lib/api/common/permissions.dart b/lib/api/common/permissions.dart index 8696f317..e0c76491 100644 --- a/lib/api/common/permissions.dart +++ b/lib/api/common/permissions.dart @@ -11,7 +11,9 @@ final class Permissions { bool has(Permission permission) => _permissions.contains(permission); factory Permissions.fromInt(int raw) { - final permissions = Permission.values.where((permission) => raw & permission.value == permission.value).toList(); + final permissions = Permission.values + .where((permission) => raw & permission.value == permission.value) + .toList(); return Permissions(raw, permissions); } } diff --git a/lib/api/common/polls/poll_answer.dart b/lib/api/common/polls/poll_answer.dart index 1086aec3..510998c1 100644 --- a/lib/api/common/polls/poll_answer.dart +++ b/lib/api/common/polls/poll_answer.dart @@ -11,12 +11,14 @@ final class PollAnswer { return { 'poll_media': { 'text': content, - ...?Helper.createOrNull(field: emoji, fn: () => { - 'emoji': { - 'id': emoji?.id, - 'name': emoji?.name, - }, - }) + ...?Helper.createOrNull( + field: emoji, + fn: () => { + 'emoji': { + 'id': emoji?.id, + 'name': emoji?.name, + }, + }) } }; } diff --git a/lib/api/common/polls/poll_builder.dart b/lib/api/common/polls/poll_builder.dart index 75039fb4..d6dfc32c 100644 --- a/lib/api/common/polls/poll_builder.dart +++ b/lib/api/common/polls/poll_builder.dart @@ -11,12 +11,12 @@ final class PollBuilder { bool _isAllowMultiple = false; PollLayout _layout = PollLayout.initial; - PollBuilder setQuestion({ required String question, PartialEmoji? emoji }) { + PollBuilder setQuestion({required String question, PartialEmoji? emoji}) { _question = PollQuestion(content: question, emoji: emoji); return this; } - PollBuilder addAnswer({ required String answer, PartialEmoji? emoji }) { + PollBuilder addAnswer({required String answer, PartialEmoji? emoji}) { _answers.add(PollAnswer(content: answer, emoji: emoji)); return this; } diff --git a/lib/api/common/presence.dart b/lib/api/common/presence.dart index d2963d2e..d3a07e3f 100644 --- a/lib/api/common/presence.dart +++ b/lib/api/common/presence.dart @@ -15,12 +15,13 @@ final class Presence { }); factory Presence.fromJson(Map json) { - return Presence( since: json['since'] != null ? DateTime.parse(json['since']) : null, - activities: List.from(json['activities'].map((e) => Activity.fromJson(e))), - status: StatusType.values.firstWhere((element) => element.value == json['status']), + activities: List.from( + json['activities'].map((e) => Activity.fromJson(e))), + status: StatusType.values + .firstWhere((element) => element.value == json['status']), afk: json['afk'] ?? false, ); } -} \ No newline at end of file +} diff --git a/lib/api/common/types/channel_type.dart b/lib/api/common/types/channel_type.dart index 6168e4bc..202d6932 100644 --- a/lib/api/common/types/channel_type.dart +++ b/lib/api/common/types/channel_type.dart @@ -1,6 +1,6 @@ import 'package:mineral/api/common/types/enhanced_enum.dart'; -enum ChannelType implements EnhancedEnum{ +enum ChannelType implements EnhancedEnum { guildText(0), dm(1), guildVoice(2), @@ -35,8 +35,5 @@ enum ChannelType implements EnhancedEnum{ guildMedia ]; - static List privateTypes = [ - dm, - groupDm - ]; + static List privateTypes = [dm, groupDm]; } diff --git a/lib/api/common/types/interaction_type.dart b/lib/api/common/types/interaction_type.dart index d516a97a..0e232338 100644 --- a/lib/api/common/types/interaction_type.dart +++ b/lib/api/common/types/interaction_type.dart @@ -7,4 +7,4 @@ enum InteractionType { final int value; const InteractionType(this.value); -} \ No newline at end of file +} diff --git a/lib/api/common/types/message_flag_type.dart b/lib/api/common/types/message_flag_type.dart index 430bb0e5..a2e58f45 100644 --- a/lib/api/common/types/message_flag_type.dart +++ b/lib/api/common/types/message_flag_type.dart @@ -11,7 +11,6 @@ enum MessageFlagType { suppressNotifications(1 << 12), voiceMessage(1 << 13); - final int value; const MessageFlagType(this.value); } diff --git a/lib/api/common/types/status_type.dart b/lib/api/common/types/status_type.dart index baf662b0..caaed009 100644 --- a/lib/api/common/types/status_type.dart +++ b/lib/api/common/types/status_type.dart @@ -9,4 +9,4 @@ enum StatusType implements EnhancedEnum { @override final String value; const StatusType(this.value); -} \ No newline at end of file +} diff --git a/lib/api/private/channels/private_channel.dart b/lib/api/private/channels/private_channel.dart index 30e64575..8f491c70 100644 --- a/lib/api/private/channels/private_channel.dart +++ b/lib/api/private/channels/private_channel.dart @@ -17,7 +17,8 @@ final class PrivateChannel extends Channel { @override ChannelType get type => _properties.type; - String get name => _properties.name ?? recipients.map((e) => e.username).join(', '); + String get name => + _properties.name ?? recipients.map((e) => e.username).join(', '); String get description => _properties.description!; diff --git a/lib/api/private/private_message.dart b/lib/api/private/private_message.dart index d85bb7a6..960738f5 100644 --- a/lib/api/private/private_message.dart +++ b/lib/api/private/private_message.dart @@ -30,7 +30,8 @@ final class PrivateMessage implements Message { final User author; - PrivateMessage(this._properties, { + PrivateMessage( + this._properties, { required this.userId, required this.author, }); diff --git a/lib/api/private/user.dart b/lib/api/private/user.dart index ddefef74..bb85ff48 100644 --- a/lib/api/private/user.dart +++ b/lib/api/private/user.dart @@ -21,7 +21,6 @@ final class User { final DateTime? createdAt; Presence? presence; - User({ required this.id, required this.username, diff --git a/lib/api/server/channels/server_announcement_channel.dart b/lib/api/server/channels/server_announcement_channel.dart index 10c66a0c..11ab446a 100644 --- a/lib/api/server/channels/server_announcement_channel.dart +++ b/lib/api/server/channels/server_announcement_channel.dart @@ -43,7 +43,8 @@ final class ServerAnnouncementChannel extends ServerChannel { ServerAnnouncementChannel(this._properties) : _methods = ChannelMethods(_properties.id); - Future setName(String name, {String? reason}) => _methods.setName(name, reason); + Future setName(String name, {String? reason}) => + _methods.setName(name, reason); Future setDescription(String description, {String? reason}) => _methods.setDescription(description, reason); @@ -54,7 +55,8 @@ final class ServerAnnouncementChannel extends ServerChannel { Future setPosition(int position, {String? reason}) => _methods.setPosition(position, reason); - Future setNsfw(bool nsfw, {String? reason}) => _methods.setNsfw(nsfw, reason); + Future setNsfw(bool nsfw, {String? reason}) => + _methods.setNsfw(nsfw, reason); Future delete({String? reason}) => _methods.delete(reason); } diff --git a/lib/api/server/channels/server_category_channel.dart b/lib/api/server/channels/server_category_channel.dart index 0679b57e..50ec62f2 100644 --- a/lib/api/server/channels/server_category_channel.dart +++ b/lib/api/server/channels/server_category_channel.dart @@ -29,9 +29,11 @@ final class ServerCategoryChannel extends ServerChannel { @override late final Server server; - ServerCategoryChannel(this._properties): _methods = ChannelMethods(_properties.id); + ServerCategoryChannel(this._properties) + : _methods = ChannelMethods(_properties.id); - Future setName(String name, {String? reason}) => _methods.setName(name, reason); + Future setName(String name, {String? reason}) => + _methods.setName(name, reason); Future setPosition(int position, {String? reason}) => _methods.setPosition(position, reason); diff --git a/lib/api/server/channels/server_stage_channel.dart b/lib/api/server/channels/server_stage_channel.dart index 79ebf655..b911f16f 100644 --- a/lib/api/server/channels/server_stage_channel.dart +++ b/lib/api/server/channels/server_stage_channel.dart @@ -38,9 +38,11 @@ final class ServerStageChannel extends ServerChannel { late final ServerCategoryChannel? category; - ServerStageChannel(this._properties) : _methods = ChannelMethods(_properties.id); + ServerStageChannel(this._properties) + : _methods = ChannelMethods(_properties.id); - Future setName(String name, {String? reason}) => _methods.setName(name, reason); + Future setName(String name, {String? reason}) => + _methods.setName(name, reason); Future setDescription(String description, {String? reason}) => _methods.setDescription(description, reason); @@ -51,19 +53,27 @@ final class ServerStageChannel extends ServerChannel { Future setPosition(int position, {String? reason}) => _methods.setPosition(position, reason); - Future setNsfw(bool nsfw, {String? reason}) => _methods.setNsfw(nsfw, reason); + Future setNsfw(bool nsfw, {String? reason}) => + _methods.setNsfw(nsfw, reason); Future setRateLimitPerUser(int rateLimitPerUser, {String? reason}) => _methods.setRateLimitPerUser(rateLimitPerUser, reason); - Future setDefaultAutoArchiveDuration(int defaultAutoArchiveDuration, {String? reason}) => - _methods.setDefaultAutoArchiveDuration(defaultAutoArchiveDuration, reason); + Future setDefaultAutoArchiveDuration(int defaultAutoArchiveDuration, + {String? reason}) => + _methods.setDefaultAutoArchiveDuration( + defaultAutoArchiveDuration, reason); Future setDefaultThreadRateLimitPerUser(int value, {String? reason}) => _methods.setDefaultThreadRateLimitPerUser(value, reason); - Future send({String? content, List? embeds, Poll? poll}) => - _methods.send(guildId: _properties.serverId, content: content, embeds: embeds, poll: poll); + Future send( + {String? content, List? embeds, Poll? poll}) => + _methods.send( + guildId: _properties.serverId, + content: content, + embeds: embeds, + poll: poll); Future delete({String? reason}) => _methods.delete(reason); } diff --git a/lib/api/server/channels/server_text_channel.dart b/lib/api/server/channels/server_text_channel.dart index 3d07fda5..5245f186 100644 --- a/lib/api/server/channels/server_text_channel.dart +++ b/lib/api/server/channels/server_text_channel.dart @@ -38,9 +38,11 @@ final class ServerTextChannel extends ServerChannel { late final ServerCategoryChannel? category; - ServerTextChannel(this._properties) : _methods = ChannelMethods(_properties.id); + ServerTextChannel(this._properties) + : _methods = ChannelMethods(_properties.id); - Future setName(String name, {String? reason}) => _methods.setName(name, reason); + Future setName(String name, {String? reason}) => + _methods.setName(name, reason); Future setDescription(String description, {String? reason}) => _methods.setDescription(description, reason); @@ -51,13 +53,16 @@ final class ServerTextChannel extends ServerChannel { Future setPosition(int position, {String? reason}) => _methods.setPosition(position, reason); - Future setNsfw(bool nsfw, {String? reason}) => _methods.setNsfw(nsfw, reason); + Future setNsfw(bool nsfw, {String? reason}) => + _methods.setNsfw(nsfw, reason); Future setRateLimitPerUser(int rateLimitPerUser, {String? reason}) => _methods.setRateLimitPerUser(rateLimitPerUser, reason); - Future setDefaultAutoArchiveDuration(int defaultAutoArchiveDuration, {String? reason}) => - _methods.setDefaultAutoArchiveDuration(defaultAutoArchiveDuration, reason); + Future setDefaultAutoArchiveDuration(int defaultAutoArchiveDuration, + {String? reason}) => + _methods.setDefaultAutoArchiveDuration( + defaultAutoArchiveDuration, reason); Future setDefaultThreadRateLimitPerUser(int value, {String? reason}) => _methods.setDefaultThreadRateLimitPerUser(value, reason); diff --git a/lib/api/server/channels/server_voice_channel.dart b/lib/api/server/channels/server_voice_channel.dart index 778694d9..113b5805 100644 --- a/lib/api/server/channels/server_voice_channel.dart +++ b/lib/api/server/channels/server_voice_channel.dart @@ -36,9 +36,11 @@ final class ServerVoiceChannel extends ServerChannel { late final ServerCategoryChannel? category; - ServerVoiceChannel(this._properties) : _methods = ChannelMethods(_properties.id); + ServerVoiceChannel(this._properties) + : _methods = ChannelMethods(_properties.id); - Future setName(String name, {String? reason}) => _methods.setName(name, reason); + Future setName(String name, {String? reason}) => + _methods.setName(name, reason); Future setCategory(String categoryId, {String? reason}) => _methods.setCategory(categoryId, reason); @@ -46,16 +48,20 @@ final class ServerVoiceChannel extends ServerChannel { Future setPosition(int position, {String? reason}) => _methods.setPosition(position, reason); - Future setNsfw(bool nsfw, {String? reason}) => _methods.setNsfw(nsfw, reason); + Future setNsfw(bool nsfw, {String? reason}) => + _methods.setNsfw(nsfw, reason); Future setRateLimitPerUser(int rateLimitPerUser, {String? reason}) => _methods.setRateLimitPerUser(rateLimitPerUser, reason); - Future setBitrate(int bitrate, {String? reason}) => _methods.setBitrate(bitrate, reason); + Future setBitrate(int bitrate, {String? reason}) => + _methods.setBitrate(bitrate, reason); - Future setUserLimit(int userLimit, {String? reason}) => _methods.setUserLimit(userLimit, reason); + Future setUserLimit(int userLimit, {String? reason}) => + _methods.setUserLimit(userLimit, reason); - Future setRtcRegion(String rtcRegion, {String? reason}) => _methods.setRtcRegion(rtcRegion, reason); + Future setRtcRegion(String rtcRegion, {String? reason}) => + _methods.setRtcRegion(rtcRegion, reason); Future setVideoQuality(VideoQuality quality, {String? reason}) => _methods.setVideoQuality(quality, reason); diff --git a/lib/api/server/channels/thread_channel.dart b/lib/api/server/channels/thread_channel.dart index 0e9e5271..3e464edf 100644 --- a/lib/api/server/channels/thread_channel.dart +++ b/lib/api/server/channels/thread_channel.dart @@ -84,19 +84,34 @@ class ThreadChannel extends ServerChannel { _methods = ChannelMethods(id); } - Future setName(String name, {String? reason}) => _methods.setName(name, reason); - - Future setDescription(String description, {String? reason}) => _methods.setDescription(description, reason); - - Future setRateLimitPerUser(int rateLimitPerUser, {String? reason}) => _methods.setRateLimitPerUser(rateLimitPerUser, reason); - - Future setDefaultAutoArchiveDuration(int defaultAutoArchiveDuration, {String? reason}) => - _methods.setDefaultAutoArchiveDuration(defaultAutoArchiveDuration, reason); - - Future setDefaultThreadRateLimitPerUser(int value, {String? reason}) => _methods.setDefaultThreadRateLimitPerUser(value, reason); - - Future send({String? content, List? embeds, Poll? poll, List? components}) => - _methods.send(guildId: serverId, content: content, embeds: embeds, poll: poll, components: components); + Future setName(String name, {String? reason}) => + _methods.setName(name, reason); + + Future setDescription(String description, {String? reason}) => + _methods.setDescription(description, reason); + + Future setRateLimitPerUser(int rateLimitPerUser, {String? reason}) => + _methods.setRateLimitPerUser(rateLimitPerUser, reason); + + Future setDefaultAutoArchiveDuration(int defaultAutoArchiveDuration, + {String? reason}) => + _methods.setDefaultAutoArchiveDuration( + defaultAutoArchiveDuration, reason); + + Future setDefaultThreadRateLimitPerUser(int value, {String? reason}) => + _methods.setDefaultThreadRateLimitPerUser(value, reason); + + Future send( + {String? content, + List? embeds, + Poll? poll, + List? components}) => + _methods.send( + guildId: serverId, + content: content, + embeds: embeds, + poll: poll, + components: components); Future delete({String? reason}) => _methods.delete(reason); } diff --git a/lib/api/server/enums/thread_type.dart b/lib/api/server/enums/thread_type.dart index 1c803b9f..2d00e2c5 100644 --- a/lib/api/server/enums/thread_type.dart +++ b/lib/api/server/enums/thread_type.dart @@ -1,4 +1,4 @@ enum ThreadType { private, public; -} \ No newline at end of file +} diff --git a/lib/api/server/managers/channel_manager.dart b/lib/api/server/managers/channel_manager.dart index 0009676a..8c9eb641 100644 --- a/lib/api/server/managers/channel_manager.dart +++ b/lib/api/server/managers/channel_manager.dart @@ -18,13 +18,16 @@ final class ChannelManager { ChannelManager(this._channels, Map json) { _namedChannels - ..putIfAbsent(_ServerNamedChannel.afkChannel, () => json['afk_channel_id']) - ..putIfAbsent(_ServerNamedChannel.systemChannel, () => json['system_channel_id']) - ..putIfAbsent(_ServerNamedChannel.rulesChannel, () => json['rules_channel_id']) ..putIfAbsent( - _ServerNamedChannel.publicUpdatesChannel, () => json['public_updates_channel_id']) + _ServerNamedChannel.afkChannel, () => json['afk_channel_id']) ..putIfAbsent( - _ServerNamedChannel.safetyAlertsChannel, () => json['safety_alerts_channel_id']); + _ServerNamedChannel.systemChannel, () => json['system_channel_id']) + ..putIfAbsent( + _ServerNamedChannel.rulesChannel, () => json['rules_channel_id']) + ..putIfAbsent(_ServerNamedChannel.publicUpdatesChannel, + () => json['public_updates_channel_id']) + ..putIfAbsent(_ServerNamedChannel.safetyAlertsChannel, + () => json['safety_alerts_channel_id']); } Map get list => _channels; @@ -35,23 +38,23 @@ final class ChannelManager { _channels.values.firstWhere((element) => element.id.value == id, orElse: () => throw Exception('Channel not found')) as T; - ServerVoiceChannel? get afkChannel => - getOrNull(_namedChannels[_ServerNamedChannel.afkChannel]); + ServerVoiceChannel? get afkChannel => getOrNull( + _namedChannels[_ServerNamedChannel.afkChannel]); - ServerTextChannel? get systemChannel => - getOrNull(_namedChannels[_ServerNamedChannel.systemChannel]); + ServerTextChannel? get systemChannel => getOrNull( + _namedChannels[_ServerNamedChannel.systemChannel]); - ServerTextChannel? get rulesChannel => - getOrNull(_namedChannels[_ServerNamedChannel.rulesChannel]); + ServerTextChannel? get rulesChannel => getOrNull( + _namedChannels[_ServerNamedChannel.rulesChannel]); - ServerTextChannel? get publicUpdatesChannel => - getOrNull(_namedChannels[_ServerNamedChannel.publicUpdatesChannel]); + ServerTextChannel? get publicUpdatesChannel => getOrNull( + _namedChannels[_ServerNamedChannel.publicUpdatesChannel]); - ServerTextChannel? get safetyAlertsChannel => - getOrNull(_namedChannels[_ServerNamedChannel.safetyAlertsChannel]); + ServerTextChannel? get safetyAlertsChannel => getOrNull( + _namedChannels[_ServerNamedChannel.safetyAlertsChannel]); - ServerTextChannel? get widgetChannel => - getOrNull(_namedChannels[_ServerNamedChannel.widgetChannel]); + ServerTextChannel? get widgetChannel => getOrNull( + _namedChannels[_ServerNamedChannel.widgetChannel]); factory ChannelManager.fromList(List channels, payload) { return ChannelManager( diff --git a/lib/api/server/managers/emoji_manager.dart b/lib/api/server/managers/emoji_manager.dart index f07de113..5ff432bc 100644 --- a/lib/api/server/managers/emoji_manager.dart +++ b/lib/api/server/managers/emoji_manager.dart @@ -10,7 +10,8 @@ final class EmojiManager { Map get list => _emojis; factory EmojiManager.fromList(List roles, List emojis) { - return EmojiManager(Map.from(emojis.fold({}, (value, element) { + return EmojiManager( + Map.from(emojis.fold({}, (value, element) { return {...value, element.id: element}; }))); } diff --git a/lib/api/server/managers/member_manager.dart b/lib/api/server/managers/member_manager.dart index faec4c94..b058c55a 100644 --- a/lib/api/server/managers/member_manager.dart +++ b/lib/api/server/managers/member_manager.dart @@ -9,27 +9,30 @@ final class MemberManager { Map get list => _members; Map get humans { - return _members.entries.where((element) => !element.value.isBot).fold({}, (value, element) { + return _members.entries.where((element) => !element.value.isBot).fold({}, + (value, element) { return {...value, element.key: element.value}; }); } Map get bots { - return _members.entries.where((element) => element.value.isBot).fold({}, (value, element) { + return _members.entries.where((element) => element.value.isBot).fold({}, + (value, element) { return {...value, element.key: element.value}; }); } Member? get(String? id) => _members[id != null ? Snowflake(id) : null]; - Member getOrFail(String id, {String? error}) => _members.values - .firstWhere((element) => element.id.value == id, orElse: () => throw error ?? 'Member not found'); - + Member getOrFail(String id, {String? error}) => + _members.values.firstWhere((element) => element.id.value == id, + orElse: () => throw error ?? 'Member not found'); late final int maxInGuild; factory MemberManager.fromList(List payload) { - final members = Map.from(payload.fold({}, (value, element) { + final members = + Map.from(payload.fold({}, (value, element) { return {...value, element.id: element}; })); diff --git a/lib/api/server/managers/member_role_manager.dart b/lib/api/server/managers/member_role_manager.dart index 489c35c8..d6a30be9 100644 --- a/lib/api/server/managers/member_role_manager.dart +++ b/lib/api/server/managers/member_role_manager.dart @@ -19,17 +19,26 @@ final class MemberRoleManager { Future add(Snowflake roleId, {String? reason}) async { return _roleMethods.addRole( - memberId: member.id, serverId: server.id, roleId: roleId, reason: reason); + memberId: member.id, + serverId: server.id, + roleId: roleId, + reason: reason); } Future remove(Snowflake roleId, {String? reason}) async { return _roleMethods.removeRole( - memberId: member.id, serverId: server.id, roleId: roleId, reason: reason); + memberId: member.id, + serverId: server.id, + roleId: roleId, + reason: reason); } Future sync(List roleIds, {String? reason}) async { return _roleMethods.syncRoles( - memberId: member.id, serverId: server.id, roleIds: roleIds, reason: reason); + memberId: member.id, + serverId: server.id, + roleIds: roleIds, + reason: reason); } Future clear({String? reason}) async { diff --git a/lib/api/server/managers/threads_manager.dart b/lib/api/server/managers/threads_manager.dart index 66022a76..51925a6d 100644 --- a/lib/api/server/managers/threads_manager.dart +++ b/lib/api/server/managers/threads_manager.dart @@ -28,9 +28,9 @@ final class ThreadsManager { factory ThreadsManager.fromList(List threads, payload) { return ThreadsManager( - Map.from(threads.fold({}, (value, element) { - return {...value, element.id: element}; - })), + Map.from(threads.fold({}, (value, element) { + return {...value, element.id: element}; + })), ); } } diff --git a/lib/api/server/member.dart b/lib/api/server/member.dart index 59c2fa64..e8947f73 100644 --- a/lib/api/server/member.dart +++ b/lib/api/server/member.dart @@ -41,28 +41,40 @@ final class Member { final MemberFlagsManager flags; Presence? presence; - bool canByPassVerification() => flags.list.contains(MemberFlag.bypassedVerification); + bool canByPassVerification() => + flags.list.contains(MemberFlag.bypassedVerification); - bool hasCompletedOnboarding() => flags.list.contains(MemberFlag.completedOnboarding); + bool hasCompletedOnboarding() => + flags.list.contains(MemberFlag.completedOnboarding); - bool hasStartedOnboarding() => flags.list.contains(MemberFlag.startedOnboarding); + bool hasStartedOnboarding() => + flags.list.contains(MemberFlag.startedOnboarding); bool hasRejoined() => flags.list.contains(MemberFlag.didRejoin); - Future setUsername(String value, String? reason) => _memberMethods.updateMember( - serverId: server.id, memberId: id, payload: {'username': value}, reason: reason); + Future setUsername(String value, String? reason) => + _memberMethods.updateMember( + serverId: server.id, + memberId: id, + payload: {'username': value}, + reason: reason); - Future setNickname(String value, String? reason) => _memberMethods.updateMember( - serverId: server.id, memberId: id, payload: {'nick': value}, reason: reason); + Future setNickname(String value, String? reason) => + _memberMethods.updateMember( + serverId: server.id, + memberId: id, + payload: {'nick': value}, + reason: reason); - Future ban({Duration? deleteSince, String? reason}) => - _memberMethods.banMember(serverId: server.id, memberId: id, deleteSince: deleteSince); + Future ban({Duration? deleteSince, String? reason}) => _memberMethods + .banMember(serverId: server.id, memberId: id, deleteSince: deleteSince); - Future kick({String? reason}) => - _memberMethods.kickMember(serverId: server.id, memberId: id, reason: reason); + Future kick({String? reason}) => _memberMethods.kickMember( + serverId: server.id, memberId: id, reason: reason); Future exclude({Duration? duration, String? reason}) { - final timeout = duration != null ? DateTime.now().add(duration) : DateTime.now(); + final timeout = + duration != null ? DateTime.now().add(duration) : DateTime.now(); return _memberMethods.updateMember( serverId: server.id, @@ -78,21 +90,31 @@ final class Member { payload: {'communication_disabled_until': null}); Future enableMfa({String? reason}) => _memberMethods.updateMember( - serverId: server.id, memberId: id, payload: {'mfa_enable': true}, reason: reason); + serverId: server.id, + memberId: id, + payload: {'mfa_enable': true}, + reason: reason); Future disableMfa({String? reason}) => _memberMethods.updateMember( - serverId: server.id, memberId: id, payload: {'mfa_enable': false}, reason: reason); + serverId: server.id, + memberId: id, + payload: {'mfa_enable': false}, + reason: reason); Future toggleMfa({String? reason}) => mfaEnabled ? disableMfa(reason: reason) : enableMfa(reason: reason); Future edit(MemberBuilder builder, {String? reason}) => - _memberMethods.updateMember(serverId: server.id, memberId: id, reason: reason, payload: { - 'nick': nickname, - 'mute': builder.isMuted, - 'deaf': builder.isDeafened, - 'exclude': builder.isExcluded, - }); + _memberMethods.updateMember( + serverId: server.id, + memberId: id, + reason: reason, + payload: { + 'nick': nickname, + 'mute': builder.isMuted, + 'deaf': builder.isDeafened, + 'exclude': builder.isExcluded, + }); Member({ required this.id, diff --git a/lib/api/server/member_flags.dart b/lib/api/server/member_flags.dart index 7e87db97..65547789 100644 --- a/lib/api/server/member_flags.dart +++ b/lib/api/server/member_flags.dart @@ -17,11 +17,12 @@ final class MemberFlagsManager { MemberFlagsManager(this._flags); - Future allowBypassVerification({String? reason}) => _memberMethods.updateMember( - serverId: server.id, - memberId: member.id, - payload: {'flags': MemberFlag.bypassedVerification.value}, - reason: reason); + Future allowBypassVerification({String? reason}) => + _memberMethods.updateMember( + serverId: server.id, + memberId: member.id, + payload: {'flags': MemberFlag.bypassedVerification.value}, + reason: reason); Future disallowBypassVerification({String? reason}) { final currentFlags = _flags.fold(0, (acc, element) => acc + element.value); @@ -29,7 +30,9 @@ final class MemberFlagsManager { return _memberMethods.updateMember( serverId: server.id, memberId: member.id, - payload: {'flags': currentFlags - MemberFlag.bypassedVerification.value}, + payload: { + 'flags': currentFlags - MemberFlag.bypassedVerification.value + }, reason: reason); } @@ -37,6 +40,9 @@ final class MemberFlagsManager { final currentFlags = flags.fold(0, (acc, element) => acc + element.value); return _memberMethods.updateMember( - serverId: server.id, memberId: member.id, payload: {'flags': currentFlags}, reason: reason); + serverId: server.id, + memberId: member.id, + payload: {'flags': currentFlags}, + reason: reason); } } diff --git a/lib/api/server/server_message.dart b/lib/api/server/server_message.dart index d3ed4f6d..2a894a84 100644 --- a/lib/api/server/server_message.dart +++ b/lib/api/server/server_message.dart @@ -28,7 +28,8 @@ final class ServerMessage extends Message { final Member author; - ServerMessage(this._properties, { + ServerMessage( + this._properties, { required this.author, }); } diff --git a/lib/api/server/threads/thread_metadata.dart b/lib/api/server/threads/thread_metadata.dart index 55d27e4d..ec6dce51 100644 --- a/lib/api/server/threads/thread_metadata.dart +++ b/lib/api/server/threads/thread_metadata.dart @@ -17,14 +17,17 @@ final class ThreadMetadata { this.archiveTimestamp, }); - factory ThreadMetadata.serialize(Map json, ChannelType type) { + factory ThreadMetadata.serialize( + Map json, ChannelType type) { return ThreadMetadata( archived: json['archived'], autoArchiveDuration: json['auto_archive_duration'], locked: json['locked'], isPublic: type == ChannelType.guildPublicThread, invitable: json['invitable'], - archiveTimestamp: json['archive_timestamp'] != null ? DateTime.parse(json['archive_timestamp']) : null, + archiveTimestamp: json['archive_timestamp'] != null + ? DateTime.parse(json['archive_timestamp']) + : null, ); } -} \ No newline at end of file +} diff --git a/lib/core/container.dart b/lib/core/container.dart index 3d2b3f5f..c3e904ee 100644 --- a/lib/core/container.dart +++ b/lib/core/container.dart @@ -1,9 +1,12 @@ import 'package:mineral/infrastructure/internals/container/ioc_container.dart'; -import 'package:mineral/infrastructure/internals/environment/environment.dart' as env_service; -import 'package:mineral/infrastructure/services/logger/logger.dart' as logger_service; +import 'package:mineral/infrastructure/internals/environment/environment.dart' + as env_service; +import 'package:mineral/infrastructure/services/logger/logger.dart' + as logger_service; mixin Logger { - logger_service.LoggerContract get logger => ioc.resolve(); + logger_service.LoggerContract get logger => + ioc.resolve(); } mixin Environment { diff --git a/lib/domains/commands/command_context.dart b/lib/domains/commands/command_context.dart index 9c66f6ee..0451119b 100644 --- a/lib/domains/commands/command_context.dart +++ b/lib/domains/commands/command_context.dart @@ -12,4 +12,4 @@ abstract class CommandContext { required this.token, required this.version, }); -} \ No newline at end of file +} diff --git a/lib/domains/commands/command_interaction_dispatcher.dart b/lib/domains/commands/command_interaction_dispatcher.dart index 821616c2..936d053a 100644 --- a/lib/domains/commands/command_interaction_dispatcher.dart +++ b/lib/domains/commands/command_interaction_dispatcher.dart @@ -10,7 +10,8 @@ import 'package:mineral/domains/commands/contexts/server_command_context.dart'; import 'package:mineral/infrastructure/internals/interactions/types/interaction_dispatcher_contract.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; -final class CommandInteractionDispatcher implements InteractionDispatcherContract { +final class CommandInteractionDispatcher + implements InteractionDispatcherContract { @override InteractionType get type => InteractionType.applicationCommand; @@ -24,12 +25,14 @@ final class CommandInteractionDispatcher implements InteractionDispatcherContrac await _handleCommand(data); } - Future _handleGroups(Map data, Map group) async { + Future _handleGroups( + Map data, Map group) async { data['data']['options'] = group['options']; return _handleSubCommand(data, group); } - Future _handleSubCommand(Map data, Map option) async { + Future _handleSubCommand( + Map data, Map option) async { data['data']['name'] = "${data['data']['name']}.${option['name']}"; data['data']['options'] = option['options']; @@ -39,7 +42,8 @@ final class CommandInteractionDispatcher implements InteractionDispatcherContrac Future _handleCommand(Map data) async { if (data['data']['options'] != null) { for (final option in data['data']['options']) { - final type = CommandType.values.firstWhereOrNull((e) => e.value == option['type']); + final type = CommandType.values + .firstWhereOrNull((e) => e.value == option['type']); if (type == null) { continue; @@ -64,7 +68,8 @@ final class CommandInteractionDispatcher implements InteractionDispatcherContrac if (data['data']['options'] != null) { for (final option in data['data']['options']) { - final type = CommandOptionType.values.firstWhereOrNull((e) => e.value == option['type']); + final type = CommandOptionType.values + .firstWhereOrNull((e) => e.value == option['type']); if (type == null) { _marshaller.logger.warn("Unknown option type: ${option['type']}"); @@ -74,12 +79,15 @@ final class CommandInteractionDispatcher implements InteractionDispatcherContrac options[Symbol(option['name'])] = switch (type) { CommandOptionType.user => switch (commandContext) { ServerCommandContext() => await _marshaller.dataStore.member - .getMember(serverId: commandContext.server.id, memberId: option['value']), + .getMember( + serverId: commandContext.server.id, + memberId: option['value']), _ => _marshaller.serializers.user.serialize(option['value']), }, CommandOptionType.channel => await _marshaller.serializers.channels.serialize(option['value']), - CommandOptionType.role => await _marshaller.serializers.role.serialize(option['value']), + CommandOptionType.role => + await _marshaller.serializers.role.serialize(option['value']), // TODO attachement _ => option['value'], }; diff --git a/lib/domains/commands/command_interaction_manager.dart b/lib/domains/commands/command_interaction_manager.dart index 8066735c..a1ef282f 100644 --- a/lib/domains/commands/command_interaction_manager.dart +++ b/lib/domains/commands/command_interaction_manager.dart @@ -46,7 +46,7 @@ final class CommandInteractionManager throw Exception('Command $command already exists'); } - final name = switch(command) { + final name = switch (command) { final CommandDeclarationBuilder command => command.name, final CommandDefinitionBuilder definition => definition.command.name, final _ => throw Exception('Unknown command type') @@ -57,7 +57,8 @@ final class CommandInteractionManager } final handlers = switch (command) { - final CommandDeclarationBuilder command => command.reduceHandlers(command.name!), + final CommandDeclarationBuilder command => + command.reduceHandlers(command.name!), final CommandDefinitionBuilder definition => definition.command.reduceHandlers(definition.command.name!), final _ => throw Exception('Unknown command type') diff --git a/lib/domains/commands/contexts/global_command_context.dart b/lib/domains/commands/contexts/global_command_context.dart index 2e509b3f..20b1e23c 100644 --- a/lib/domains/commands/contexts/global_command_context.dart +++ b/lib/domains/commands/contexts/global_command_context.dart @@ -33,8 +33,10 @@ final class GlobalCommandContext implements CommandContext { applicationId: Snowflake(payload['application_id']), token: payload['token'], version: payload['version'], - user: await marshaller.dataStore.user.getUser(Snowflake(payload['member']['user']['id'])), - channel: await marshaller.dataStore.channel.getChannel(Snowflake(payload['channel_id'])), + user: await marshaller.dataStore.user + .getUser(Snowflake(payload['member']['user']['id'])), + channel: await marshaller.dataStore.channel + .getChannel(Snowflake(payload['channel_id'])), ); } } diff --git a/lib/domains/commands/contexts/server_command_context.dart b/lib/domains/commands/contexts/server_command_context.dart index 13ed6fbf..ee3319a0 100644 --- a/lib/domains/commands/contexts/server_command_context.dart +++ b/lib/domains/commands/contexts/server_command_context.dart @@ -48,8 +48,10 @@ final class ServerCommandContext implements CommandContext { serverId: Snowflake(payload['guild_id']), memberId: Snowflake(payload['member']['user']['id']), ), - server: await marshaller.dataStore.server.getServer(Snowflake(payload['guild_id'])), - channel: await marshaller.dataStore.channel.getChannel(Snowflake(payload['channel_id'])), + server: await marshaller.dataStore.server + .getServer(Snowflake(payload['guild_id'])), + channel: await marshaller.dataStore.channel + .getChannel(Snowflake(payload['channel_id'])), ); } } diff --git a/lib/domains/components/dialog/contexts/private_dialog_context.dart b/lib/domains/components/dialog/contexts/private_dialog_context.dart index 2cc2693a..a64d97f1 100644 --- a/lib/domains/components/dialog/contexts/private_dialog_context.dart +++ b/lib/domains/components/dialog/contexts/private_dialog_context.dart @@ -36,7 +36,8 @@ final class PrivateDialogContext implements DialogContext { interaction = Interaction(token, id); } - static Future fromMap(MarshallerContract marshaller, Map payload) async{ + static Future fromMap( + MarshallerContract marshaller, Map payload) async { return PrivateDialogContext( customId: payload['data']['custom_id'], id: Snowflake(payload['id']), diff --git a/lib/domains/components/dialog/contexts/server_dialog_context.dart b/lib/domains/components/dialog/contexts/server_dialog_context.dart index cda5ce01..f36e88bc 100644 --- a/lib/domains/components/dialog/contexts/server_dialog_context.dart +++ b/lib/domains/components/dialog/contexts/server_dialog_context.dart @@ -36,7 +36,8 @@ final class ServerDialogContext implements DialogContext { interaction = Interaction(token, id); } - static Future fromMap(MarshallerContract marshaller, Map payload) async{ + static Future fromMap( + MarshallerContract marshaller, Map payload) async { return ServerDialogContext( customId: payload['data']['custom_id'], id: Snowflake(payload['id']), diff --git a/lib/domains/components/selects/contexts/private_select_context.dart b/lib/domains/components/selects/contexts/private_select_context.dart index 59caa3cf..1f089b3f 100644 --- a/lib/domains/components/selects/contexts/private_select_context.dart +++ b/lib/domains/components/selects/contexts/private_select_context.dart @@ -40,7 +40,8 @@ final class PrivateSelectContext implements SelectContext { interaction = Interaction(token, id); } - static Future fromMap(MarshallerContract marshaller, Map payload) async { + static Future fromMap( + MarshallerContract marshaller, Map payload) async { return PrivateSelectContext( customId: payload['data']['custom_id'], id: Snowflake(payload['id']), diff --git a/lib/domains/components/selects/contexts/server_select_context.dart b/lib/domains/components/selects/contexts/server_select_context.dart index 80d85f3a..243c7772 100644 --- a/lib/domains/components/selects/contexts/server_select_context.dart +++ b/lib/domains/components/selects/contexts/server_select_context.dart @@ -40,7 +40,8 @@ final class ServerSelectContext implements SelectContext { interaction = Interaction(token, id); } - static Future fromMap(MarshallerContract marshaller, Map payload) async{ + static Future fromMap( + MarshallerContract marshaller, Map payload) async { return ServerSelectContext( customId: payload['data']['custom_id'], id: Snowflake(payload['id']), diff --git a/lib/domains/events/buckets/private_bucket.dart b/lib/domains/events/buckets/private_bucket.dart index d15ba649..c58beb02 100644 --- a/lib/domains/events/buckets/private_bucket.dart +++ b/lib/domains/events/buckets/private_bucket.dart @@ -25,7 +25,8 @@ final class PrivateBucket { void buttonClick(PrivateButtonClickEventHandler handle) => _events.make(Event.privateButtonClick, handle); - void dialogSubmit(PrivateDialogSubmitEventHandler handle, {String? customId}) => + void dialogSubmit(PrivateDialogSubmitEventHandler handle, + {String? customId}) => _events.make(Event.privateDialogSubmit, handle, customId: customId); void selectUser(PrivateUserSelectEventHandler handle, {String? customId}) => diff --git a/lib/domains/events/buckets/server_bucket.dart b/lib/domains/events/buckets/server_bucket.dart index b06198eb..4745b626 100644 --- a/lib/domains/events/buckets/server_bucket.dart +++ b/lib/domains/events/buckets/server_bucket.dart @@ -37,11 +37,14 @@ final class ServerBucket { ServerBucket(this._events); - void serverCreate(ServerCreateEventHandler handle) => _events.make(Event.serverCreate, handle); + void serverCreate(ServerCreateEventHandler handle) => + _events.make(Event.serverCreate, handle); - void serverUpdate(ServerUpdateEventHandler handle) => _events.make(Event.serverUpdate, handle); + void serverUpdate(ServerUpdateEventHandler handle) => + _events.make(Event.serverUpdate, handle); - void serverDelete(ServerDeleteEventHandler handle) => _events.make(Event.serverDelete, handle); + void serverDelete(ServerDeleteEventHandler handle) => + _events.make(Event.serverDelete, handle); void messageCreate(ServerMessageEventHandler handle) => _events.make(Event.serverMessageCreate, handle); @@ -58,7 +61,8 @@ final class ServerBucket { void channelPinsUpdate(ServerChannelPinsUpdateEventHandler handle) => _events.make(Event.serverChannelPinsUpdate, handle); - void memberAdd(ServerMemberAddEventHandler handle) => _events.make(Event.serverMemberAdd, handle); + void memberAdd(ServerMemberAddEventHandler handle) => + _events.make(Event.serverMemberAdd, handle); void memberRemove(ServerMemberRemoveEventHandler handle) => _events.make(Event.serverMemberRemove, handle); @@ -78,9 +82,11 @@ final class ServerBucket { void presenceUpdate(ServerPresenceUpdateEventHandler handle) => _events.make(Event.serverPresenceUpdate, handle); - void banAdd(ServerBanAddEventHandler handle) => _events.make(Event.serverBanAdd, handle); + void banAdd(ServerBanAddEventHandler handle) => + _events.make(Event.serverBanAdd, handle); - void banRemove(ServerBanRemoveEventHandler handle) => _events.make(Event.serverBanRemove, handle); + void banRemove(ServerBanRemoveEventHandler handle) => + _events.make(Event.serverBanRemove, handle); void emojisUpdate(ServerEmojisUpdateEventHandler handle) => _events.make(Event.serverEmojisUpdate, handle); @@ -91,16 +97,19 @@ final class ServerBucket { void buttonClick(ServerButtonClickEventHandler handle, {String? customId}) => _events.make(Event.serverButtonClick, handle, customId: customId); - void dialogSubmit(ServerDialogSubmitEventHandler handle, {String? customId}) => + void dialogSubmit(ServerDialogSubmitEventHandler handle, + {String? customId}) => _events.make(Event.serverDialogSubmit, handle, customId: customId); - void selectChannel(ServerChannelSelectEventHandler handle, {String? customId}) => + void selectChannel(ServerChannelSelectEventHandler handle, + {String? customId}) => _events.make(Event.serverChannelSelect, handle, customId: customId); void selectRole(ServerRoleSelectEventHandler handle, {String? customId}) => _events.make(Event.serverRoleSelect, handle, customId: customId); - void selectMember(ServerMemberSelectEventHandler handle, {String? customId}) => + void selectMember(ServerMemberSelectEventHandler handle, + {String? customId}) => _events.make(Event.serverMemberSelect, handle, customId: customId); void selectText(ServerTextSelectEventHandler handle, {String? customId}) => diff --git a/lib/domains/events/contracts/private/private_button_click_event.dart b/lib/domains/events/contracts/private/private_button_click_event.dart index 675004ef..08fc4d8c 100644 --- a/lib/domains/events/contracts/private/private_button_click_event.dart +++ b/lib/domains/events/contracts/private/private_button_click_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/domains/components/buttons/contexts/private_button_conte import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef PrivateButtonClickEventHandler = FutureOr Function(PrivateButtonContext); +typedef PrivateButtonClickEventHandler = FutureOr Function( + PrivateButtonContext); abstract class PrivateButtonClickEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/private/private_channel_create_event.dart b/lib/domains/events/contracts/private/private_channel_create_event.dart index e86f4469..28f00191 100644 --- a/lib/domains/events/contracts/private/private_channel_create_event.dart +++ b/lib/domains/events/contracts/private/private_channel_create_event.dart @@ -3,7 +3,8 @@ import 'dart:async'; import 'package:mineral/api/private/channels/private_channel.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef PrivateChannelCreateEventHandler = FutureOr Function(PrivateChannel); +typedef PrivateChannelCreateEventHandler = FutureOr Function( + PrivateChannel); abstract class PrivateChannelCreateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/private/private_channel_delete_event.dart b/lib/domains/events/contracts/private/private_channel_delete_event.dart index 1c45e794..9bb01286 100644 --- a/lib/domains/events/contracts/private/private_channel_delete_event.dart +++ b/lib/domains/events/contracts/private/private_channel_delete_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/api/private/channels/private_channel.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef PrivateChannelDeleteEventHandler = FutureOr Function(PrivateChannel); +typedef PrivateChannelDeleteEventHandler = FutureOr Function( + PrivateChannel); abstract class PrivateChannelDeleteEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/private/private_channel_pins_update_event.dart b/lib/domains/events/contracts/private/private_channel_pins_update_event.dart index 9a30d61b..c2f070c8 100644 --- a/lib/domains/events/contracts/private/private_channel_pins_update_event.dart +++ b/lib/domains/events/contracts/private/private_channel_pins_update_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/api/private/channels/private_channel.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef PrivateChannelPinsUpdateEventHandler = FutureOr Function(PrivateChannel?); +typedef PrivateChannelPinsUpdateEventHandler = FutureOr Function( + PrivateChannel?); abstract class PrivateChannelPinsUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/private/private_channel_update_event.dart b/lib/domains/events/contracts/private/private_channel_update_event.dart index 7de01566..4dd95f7c 100644 --- a/lib/domains/events/contracts/private/private_channel_update_event.dart +++ b/lib/domains/events/contracts/private/private_channel_update_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/api/private/channels/private_channel.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef PrivateChannelUpdateEventHandler = FutureOr Function(PrivateChannel); +typedef PrivateChannelUpdateEventHandler = FutureOr Function( + PrivateChannel); abstract class PrivateChannelUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/private/private_dialog_submit_event.dart b/lib/domains/events/contracts/private/private_dialog_submit_event.dart index 50591ac2..1a4d0484 100644 --- a/lib/domains/events/contracts/private/private_dialog_submit_event.dart +++ b/lib/domains/events/contracts/private/private_dialog_submit_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/domains/components/dialog/contexts/private_dialog_contex import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef PrivateDialogSubmitEventHandler = FutureOr Function(PrivateDialogContext); +typedef PrivateDialogSubmitEventHandler = FutureOr Function( + PrivateDialogContext); abstract class PrivateDialogSubmitEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/private/private_message_create_event.dart b/lib/domains/events/contracts/private/private_message_create_event.dart index 2e546bfa..6a36968f 100644 --- a/lib/domains/events/contracts/private/private_message_create_event.dart +++ b/lib/domains/events/contracts/private/private_message_create_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/api/private/private_message.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef PrivateMessageCreateEventHandler = FutureOr Function(PrivateMessage); +typedef PrivateMessageCreateEventHandler = FutureOr Function( + PrivateMessage); abstract class PrivateMessageCreateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/private/private_text_select_event.dart b/lib/domains/events/contracts/private/private_text_select_event.dart index 2e3fad00..b88752e5 100644 --- a/lib/domains/events/contracts/private/private_text_select_event.dart +++ b/lib/domains/events/contracts/private/private_text_select_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/domains/components/selects/contexts/private_select_conte import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef PrivateTextSelectEventHandler = FutureOr Function(PrivateSelectContext, List); +typedef PrivateTextSelectEventHandler = FutureOr Function( + PrivateSelectContext, List); abstract class PrivateTextSelectEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/private/private_user_select_event.dart b/lib/domains/events/contracts/private/private_user_select_event.dart index d350b1f2..85306311 100644 --- a/lib/domains/events/contracts/private/private_user_select_event.dart +++ b/lib/domains/events/contracts/private/private_user_select_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/domains/components/selects/contexts/private_select_conte import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef PrivateUserSelectEventHandler = FutureOr Function(PrivateSelectContext, List); +typedef PrivateUserSelectEventHandler = FutureOr Function( + PrivateSelectContext, List); abstract class PrivateUserSelectEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_ban_add_event.dart b/lib/domains/events/contracts/server/server_ban_add_event.dart index e92fb1fa..b93afc84 100644 --- a/lib/domains/events/contracts/server/server_ban_add_event.dart +++ b/lib/domains/events/contracts/server/server_ban_add_event.dart @@ -6,7 +6,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerBanAddEventHandler = FutureOr Function(Member?, User, Server); +typedef ServerBanAddEventHandler = FutureOr Function( + Member?, User, Server); abstract class ServerBanAddEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_button_click_event.dart b/lib/domains/events/contracts/server/server_button_click_event.dart index 136f0799..19f35de5 100644 --- a/lib/domains/events/contracts/server/server_button_click_event.dart +++ b/lib/domains/events/contracts/server/server_button_click_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/domains/components/buttons/contexts/server_button_contex import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerButtonClickEventHandler = FutureOr Function(ServerButtonContext); +typedef ServerButtonClickEventHandler = FutureOr Function( + ServerButtonContext); abstract class ServerButtonClickEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_channel_create_event.dart b/lib/domains/events/contracts/server/server_channel_create_event.dart index 7a7361b2..195d4b8b 100644 --- a/lib/domains/events/contracts/server/server_channel_create_event.dart +++ b/lib/domains/events/contracts/server/server_channel_create_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/api/server/channels/server_channel.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerChannelCreateEventHandler = FutureOr Function(ServerChannel channel); +typedef ServerChannelCreateEventHandler = FutureOr Function( + ServerChannel channel); abstract class ServerChannelCreateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_channel_delete_event.dart b/lib/domains/events/contracts/server/server_channel_delete_event.dart index a7dacea6..398bd674 100644 --- a/lib/domains/events/contracts/server/server_channel_delete_event.dart +++ b/lib/domains/events/contracts/server/server_channel_delete_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/api/server/channels/server_channel.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerChannelDeleteEventHandler = FutureOr Function(ServerChannel?); +typedef ServerChannelDeleteEventHandler = FutureOr Function( + ServerChannel?); abstract class ServerChannelDeleteEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_channel_pins_update_event.dart b/lib/domains/events/contracts/server/server_channel_pins_update_event.dart index fec8148b..7a41d913 100644 --- a/lib/domains/events/contracts/server/server_channel_pins_update_event.dart +++ b/lib/domains/events/contracts/server/server_channel_pins_update_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerChannelPinsUpdateEventHandler = FutureOr Function(Server, ServerChannel?); +typedef ServerChannelPinsUpdateEventHandler = FutureOr Function( + Server, ServerChannel?); abstract class ServerChannelPinsUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_channel_select_event.dart b/lib/domains/events/contracts/server/server_channel_select_event.dart index 0c0eb8eb..0fdc2aef 100644 --- a/lib/domains/events/contracts/server/server_channel_select_event.dart +++ b/lib/domains/events/contracts/server/server_channel_select_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/domains/components/selects/contexts/server_select_contex import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerChannelSelectEventHandler = FutureOr Function(ServerSelectContext ctx, List channels); +typedef ServerChannelSelectEventHandler = FutureOr Function( + ServerSelectContext ctx, List channels); abstract class ServerChannelSelectEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_channel_update_event.dart b/lib/domains/events/contracts/server/server_channel_update_event.dart index 076da347..a84c6a87 100644 --- a/lib/domains/events/contracts/server/server_channel_update_event.dart +++ b/lib/domains/events/contracts/server/server_channel_update_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/api/server/channels/server_channel.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerChannelUpdateEventHandler = FutureOr Function(ServerChannel, ServerChannel); +typedef ServerChannelUpdateEventHandler = FutureOr Function( + ServerChannel, ServerChannel); abstract class ServerChannelUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_dialog_submit_event.dart b/lib/domains/events/contracts/server/server_dialog_submit_event.dart index c7d362eb..0b827168 100644 --- a/lib/domains/events/contracts/server/server_dialog_submit_event.dart +++ b/lib/domains/events/contracts/server/server_dialog_submit_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/domains/components/dialog/contexts/server_dialog_context import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerDialogSubmitEventHandler = FutureOr Function(ServerDialogContext ctx, T data); +typedef ServerDialogSubmitEventHandler = FutureOr Function( + ServerDialogContext ctx, T data); abstract class ServerDialogSubmitEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_emojis_update_event.dart b/lib/domains/events/contracts/server/server_emojis_update_event.dart index 5cacb660..df1ae590 100644 --- a/lib/domains/events/contracts/server/server_emojis_update_event.dart +++ b/lib/domains/events/contracts/server/server_emojis_update_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerEmojisUpdateEventHandler = FutureOr Function(EmojiManager, Server); +typedef ServerEmojisUpdateEventHandler = FutureOr Function( + EmojiManager, Server); abstract class ServerEmojisUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_member_select_event.dart b/lib/domains/events/contracts/server/server_member_select_event.dart index e5eb28af..44bf0752 100644 --- a/lib/domains/events/contracts/server/server_member_select_event.dart +++ b/lib/domains/events/contracts/server/server_member_select_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/domains/components/selects/contexts/server_select_contex import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerMemberSelectEventHandler = FutureOr Function(ServerSelectContext, List); +typedef ServerMemberSelectEventHandler = FutureOr Function( + ServerSelectContext, List); abstract class ServerMemberSelectEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_member_update_event.dart b/lib/domains/events/contracts/server/server_member_update_event.dart index 648aa41d..72830cbc 100644 --- a/lib/domains/events/contracts/server/server_member_update_event.dart +++ b/lib/domains/events/contracts/server/server_member_update_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerMemberUpdateEventHandler = FutureOr Function(Member, Member, Server); +typedef ServerMemberUpdateEventHandler = FutureOr Function( + Member, Member, Server); abstract class ServerMemberUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_presence_update_event.dart b/lib/domains/events/contracts/server/server_presence_update_event.dart index 759c56d9..0b124bd1 100644 --- a/lib/domains/events/contracts/server/server_presence_update_event.dart +++ b/lib/domains/events/contracts/server/server_presence_update_event.dart @@ -6,7 +6,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerPresenceUpdateEventHandler = FutureOr Function(Member, Server, Presence); +typedef ServerPresenceUpdateEventHandler = FutureOr Function( + Member, Server, Presence); abstract class ServerPresenceUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_role_select_event.dart b/lib/domains/events/contracts/server/server_role_select_event.dart index 3ae88bd4..2066ad1b 100644 --- a/lib/domains/events/contracts/server/server_role_select_event.dart +++ b/lib/domains/events/contracts/server/server_role_select_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/domains/components/selects/contexts/server_select_contex import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerRoleSelectEventHandler = FutureOr Function(ServerSelectContext, List); +typedef ServerRoleSelectEventHandler = FutureOr Function( + ServerSelectContext, List); abstract class ServerRoleSelectEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_roles_update_event.dart b/lib/domains/events/contracts/server/server_roles_update_event.dart index e6632565..2b79c2cb 100644 --- a/lib/domains/events/contracts/server/server_roles_update_event.dart +++ b/lib/domains/events/contracts/server/server_roles_update_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerRolesUpdateEventHandler = FutureOr Function(Role, Role, Server); +typedef ServerRolesUpdateEventHandler = FutureOr Function( + Role, Role, Server); abstract class ServerRolesUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_stickers_update_event.dart b/lib/domains/events/contracts/server/server_stickers_update_event.dart index 1ef6f10e..0e11b806 100644 --- a/lib/domains/events/contracts/server/server_stickers_update_event.dart +++ b/lib/domains/events/contracts/server/server_stickers_update_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerStickersUpdateEventHandler = FutureOr Function(StickerManager, Server); +typedef ServerStickersUpdateEventHandler = FutureOr Function( + StickerManager, Server); abstract class ServerStickersUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_text_select_event.dart b/lib/domains/events/contracts/server/server_text_select_event.dart index 1c8c576c..3daac274 100644 --- a/lib/domains/events/contracts/server/server_text_select_event.dart +++ b/lib/domains/events/contracts/server/server_text_select_event.dart @@ -4,7 +4,8 @@ import 'package:mineral/domains/components/selects/contexts/server_select_contex import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerTextSelectEventHandler = FutureOr Function(ServerSelectContext, List); +typedef ServerTextSelectEventHandler = FutureOr Function( + ServerSelectContext, List); abstract class ServerTextSelectEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_thread_create_event.dart b/lib/domains/events/contracts/server/server_thread_create_event.dart index f587285f..f0fe7b46 100644 --- a/lib/domains/events/contracts/server/server_thread_create_event.dart +++ b/lib/domains/events/contracts/server/server_thread_create_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerThreadCreateEventHandler = FutureOr Function(ThreadChannel, Server); +typedef ServerThreadCreateEventHandler = FutureOr Function( + ThreadChannel, Server); abstract class ServerThreadCreateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_thread_delete_event.dart b/lib/domains/events/contracts/server/server_thread_delete_event.dart index ea17e085..08c57d95 100644 --- a/lib/domains/events/contracts/server/server_thread_delete_event.dart +++ b/lib/domains/events/contracts/server/server_thread_delete_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerThreadDeleteEventHandler = FutureOr Function(ThreadChannel, Server); +typedef ServerThreadDeleteEventHandler = FutureOr Function( + ThreadChannel, Server); abstract class ServerThreadDeleteEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_thread_list_sync_event.dart b/lib/domains/events/contracts/server/server_thread_list_sync_event.dart index 01a75efc..fab1789e 100644 --- a/lib/domains/events/contracts/server/server_thread_list_sync_event.dart +++ b/lib/domains/events/contracts/server/server_thread_list_sync_event.dart @@ -6,7 +6,8 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerThreadListSyncEventHandler = FutureOr Function(List, Server); +typedef ServerThreadListSyncEventHandler = FutureOr Function( + List, Server); abstract class ServerThreadListSyncEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_thread_member_add_event.dart b/lib/domains/events/contracts/server/server_thread_member_add_event.dart index 14899e5a..d6bb04ff 100644 --- a/lib/domains/events/contracts/server/server_thread_member_add_event.dart +++ b/lib/domains/events/contracts/server/server_thread_member_add_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/channels/thread_channel.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerThreadMemberAddEventHandler = FutureOr Function(ThreadChannel, Server, Member); +typedef ServerThreadMemberAddEventHandler = FutureOr Function( + ThreadChannel, Server, Member); abstract class ServerThreadMemberAddEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_thread_member_remove_event.dart b/lib/domains/events/contracts/server/server_thread_member_remove_event.dart index d1cf2d74..a4492380 100644 --- a/lib/domains/events/contracts/server/server_thread_member_remove_event.dart +++ b/lib/domains/events/contracts/server/server_thread_member_remove_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/channels/thread_channel.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerThreadMemberRemoveEventHandler = FutureOr Function(ThreadChannel, Server, Member); +typedef ServerThreadMemberRemoveEventHandler = FutureOr Function( + ThreadChannel, Server, Member); abstract class ServerThreadMemberRemoveEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_thread_member_update_event.dart b/lib/domains/events/contracts/server/server_thread_member_update_event.dart index 844ca4c7..4135199b 100644 --- a/lib/domains/events/contracts/server/server_thread_member_update_event.dart +++ b/lib/domains/events/contracts/server/server_thread_member_update_event.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/channels/thread_channel.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerThreadMemberUpdateEventHandler = FutureOr Function(ThreadChannel, Server, Member); +typedef ServerThreadMemberUpdateEventHandler = FutureOr Function( + ThreadChannel, Server, Member); abstract class ServerThreadMemberUpdateEvent implements ListenableEvent { @override diff --git a/lib/domains/events/contracts/server/server_thread_update_event.dart b/lib/domains/events/contracts/server/server_thread_update_event.dart index 62da585e..24031908 100644 --- a/lib/domains/events/contracts/server/server_thread_update_event.dart +++ b/lib/domains/events/contracts/server/server_thread_update_event.dart @@ -5,11 +5,13 @@ import 'package:mineral/api/server/server.dart'; import 'package:mineral/domains/events/event.dart'; import 'package:mineral/domains/events/types/listenable_event.dart'; -typedef ServerThreadUpdateEventHandler = FutureOr Function(ThreadChannel, ThreadChannel, Server); +typedef ServerThreadUpdateEventHandler = FutureOr Function( + ThreadChannel, ThreadChannel, Server); abstract class ServerThreadUpdateEvent implements ListenableEvent { @override Event get event => Event.serverThreadUpdate; - FutureOr handle(ThreadChannel before, ThreadChannel after, Server server); + FutureOr handle( + ThreadChannel before, ThreadChannel after, Server server); } diff --git a/lib/domains/events/event_bucket.dart b/lib/domains/events/event_bucket.dart index 3d28c5db..ece70f6f 100644 --- a/lib/domains/events/event_bucket.dart +++ b/lib/domains/events/event_bucket.dart @@ -18,9 +18,11 @@ final class EventBucket { void make(Event event, T handle, {String? customId}) => _registerEvent(event: event, handle: handle, customId: customId); - void ready(ReadyEventHandler handle) => _registerEvent(event: Event.ready, handle: handle); + void ready(ReadyEventHandler handle) => + _registerEvent(event: Event.ready, handle: handle); void _registerEvent( {required Event event, required T handle, String? customId}) => - _kernel.eventListener.listen(event: event, handle: handle, customId: customId); + _kernel.eventListener + .listen(event: event, handle: handle, customId: customId); } diff --git a/lib/domains/events/event_dispatcher.dart b/lib/domains/events/event_dispatcher.dart index 3b4f4dc1..963cda3e 100644 --- a/lib/domains/events/event_dispatcher.dart +++ b/lib/domains/events/event_dispatcher.dart @@ -14,7 +14,10 @@ final class EventDispatcher implements EventDispatcherContract { EventDispatcher(this._events); @override - void dispatch({required Event event, required List params, bool Function(String?)? constraint}) { + void dispatch( + {required Event event, + required List params, + bool Function(String?)? constraint}) { _events.add(InternalEventParams(event, params, constraint)); } diff --git a/lib/domains/events/event_listener.dart b/lib/domains/events/event_listener.dart index a00143b7..b9d25d22 100644 --- a/lib/domains/events/event_listener.dart +++ b/lib/domains/events/event_listener.dart @@ -31,7 +31,9 @@ final class EventListener implements EventListenerContract { @override StreamSubscription listen( {required Event event, required T handle, required String? customId}) { - return _events.stream.where((element) => element.event == event).where((element) { + return _events.stream + .where((element) => element.event == event) + .where((element) { return switch (element.constraint) { final bool Function(String?) constraint => constraint(customId), _ => true diff --git a/lib/domains/providers/provider_manager.dart b/lib/domains/providers/provider_manager.dart index 3160429f..7bc4efa9 100644 --- a/lib/domains/providers/provider_manager.dart +++ b/lib/domains/providers/provider_manager.dart @@ -21,7 +21,6 @@ final class ProviderManager implements ProviderManagerContract { } } - @override Future dispose() async { for (final provider in _providers) { diff --git a/lib/infrastructure/commons/file.dart b/lib/infrastructure/commons/file.dart index 3b579163..a423d932 100644 --- a/lib/infrastructure/commons/file.dart +++ b/lib/infrastructure/commons/file.dart @@ -4,7 +4,8 @@ import 'dart:io'; import 'package:yaml/yaml.dart'; extension YamlFile on File { - Future readAsYaml({T Function(Map payload)? constructor}) async { + Future readAsYaml( + {T Function(Map payload)? constructor}) async { final stringifyContent = await readAsString(); final YamlMap yamlContent = loadYaml(stringifyContent); final Map map = {}; @@ -16,7 +17,8 @@ extension YamlFile on File { return constructor != null ? constructor(map) : map; } - T readAsYamlSync({T Function(Map payload)? constructor}) { + T readAsYamlSync( + {T Function(Map payload)? constructor}) { final stringifyContent = readAsStringSync(); final YamlMap yamlContent = loadYaml(stringifyContent); final Map map = {}; @@ -30,14 +32,16 @@ extension YamlFile on File { } extension JsonFile on File { - Future readAsJson({T Function(Map payload)? constructor}) async { + Future readAsJson( + {T Function(Map payload)? constructor}) async { final content = await readAsString(); final Map map = jsonDecode(content); return constructor != null ? constructor(map) : map; } - T readAsJsonSync({T Function(Map payload)? constructor}) { + T readAsJsonSync( + {T Function(Map payload)? constructor}) { final content = readAsStringSync(); final Map map = jsonDecode(content); diff --git a/lib/infrastructure/commons/helper.dart b/lib/infrastructure/commons/helper.dart index d228065c..444c77bb 100644 --- a/lib/infrastructure/commons/helper.dart +++ b/lib/infrastructure/commons/helper.dart @@ -1,7 +1,8 @@ import 'dart:async'; final class Helper { - static T? createOrNull({required dynamic field, required T? Function() fn}) { + static T? createOrNull( + {required dynamic field, required T? Function() fn}) { return field != null ? fn() : null; } diff --git a/lib/infrastructure/commons/utils.dart b/lib/infrastructure/commons/utils.dart index a122e570..d8b5c6f1 100644 --- a/lib/infrastructure/commons/utils.dart +++ b/lib/infrastructure/commons/utils.dart @@ -3,10 +3,12 @@ import 'dart:async'; import 'package:collection/collection.dart'; import 'package:mineral/api/common/types/enhanced_enum.dart'; -FutureOr createOrNull({required dynamic field, required FutureOr Function() fn}) async => +FutureOr createOrNull( + {required dynamic field, required FutureOr Function() fn}) async => field != null ? await fn() : null; -List bitfieldToList>(List values, int bitfield) { +List bitfieldToList>( + List values, int bitfield) { final List flags = []; for (final element in values) { @@ -18,7 +20,8 @@ List bitfieldToList>(List values, int bitfield } int listToBitfield>(List values) { - return values.fold(0, (previousValue, element) => previousValue += element.value); + return values.fold( + 0, (previousValue, element) => previousValue += element.value); } T findInEnum, R>(List values, R value) { diff --git a/lib/infrastructure/internals/cache/cache_provider_contract.dart b/lib/infrastructure/internals/cache/cache_provider_contract.dart index 35c16c2d..9901fab3 100644 --- a/lib/infrastructure/internals/cache/cache_provider_contract.dart +++ b/lib/infrastructure/internals/cache/cache_provider_contract.dart @@ -17,11 +17,13 @@ abstract interface class CacheProviderContract { FutureOr?>> getMany(List keys); - FutureOr> getOrFail(String key, {Exception Function()? onFail}); + FutureOr> getOrFail(String key, + {Exception Function()? onFail}); FutureOr?> whereKeyStartsWith(String prefix); - FutureOr> whereKeyStartsWithOrFail(String prefix, {Exception Function()? onFail}); + FutureOr> whereKeyStartsWithOrFail(String prefix, + {Exception Function()? onFail}); FutureOr has(String key); diff --git a/lib/infrastructure/internals/container/ioc_container.dart b/lib/infrastructure/internals/container/ioc_container.dart index d85877c8..91deb0ac 100644 --- a/lib/infrastructure/internals/container/ioc_container.dart +++ b/lib/infrastructure/internals/container/ioc_container.dart @@ -16,7 +16,7 @@ final class IocContainer { T resolve() { final service = _services[T]; - return switch(service) { + return switch (service) { null => throw Exception('Service not found'), _ => service, }; diff --git a/lib/infrastructure/internals/datastore/parts/channel_part.dart b/lib/infrastructure/internals/datastore/parts/channel_part.dart index b5e83613..99b282b9 100644 --- a/lib/infrastructure/internals/datastore/parts/channel_part.dart +++ b/lib/infrastructure/internals/datastore/parts/channel_part.dart @@ -24,14 +24,16 @@ final class ChannelPart implements DataStorePart { final cachedChannel = await _kernel.marshaller.cache.get(key); if (cachedChannel != null) { - return _kernel.marshaller.serializers.channels.serialize(cachedChannel) as Future; + return _kernel.marshaller.serializers.channels.serialize(cachedChannel) + as Future; } final threadKey = _kernel.marshaller.cacheKey.thread(id); final cachedThread = await _kernel.marshaller.cache.get(threadKey); if (cachedThread != null) { - return _kernel.marshaller.serializers.thread.serialize(cachedThread) as Future; + return _kernel.marshaller.serializers.thread.serialize(cachedThread) + as Future; } final response = await _kernel.dataStore.client.get('/channels/$id'); @@ -49,9 +51,12 @@ final class ChannelPart implements DataStorePart { } final response = await _kernel.dataStore.client.get('/channels/$id'); - final rawThread = await _kernel.marshaller.serializers.thread.normalize(response.body); - final thread = await _kernel.marshaller.serializers.thread.serialize(rawThread); - final parentChannel = await getChannel(Snowflake(thread.channelId)) as ServerTextChannel; + final rawThread = + await _kernel.marshaller.serializers.thread.normalize(response.body); + final thread = + await _kernel.marshaller.serializers.thread.serialize(rawThread); + final parentChannel = + await getChannel(Snowflake(thread.channelId)) as ServerTextChannel; thread ..server = await _kernel.dataStore.server.getServer(rawThread['guild_id']) @@ -60,26 +65,38 @@ final class ChannelPart implements DataStorePart { return thread; } - Future createServerChannel({required Snowflake id, required Map payload, required String? reason}) async { - final response = await _kernel.dataStore.client - .post('/guilds/$id/channels', body: payload, option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + Future createServerChannel( + {required Snowflake id, + required Map payload, + required String? reason}) async { + final response = await _kernel.dataStore.client.post('/guilds/$id/channels', + body: payload, + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); final Channel? channel = await serializeChannelResponse(response); return channel as T?; } - Future createPrivateChannel({required Snowflake id, required Snowflake recipientId}) async { - final response = await _kernel.dataStore.client.post('/users/@me/channels', body: {'recipient_id': recipientId}); + Future createPrivateChannel( + {required Snowflake id, required Snowflake recipientId}) async { + final response = await _kernel.dataStore.client + .post('/users/@me/channels', body: {'recipient_id': recipientId}); final Channel? channel = await serializeChannelResponse(response); return channel as PrivateChannel?; } - Future updateChannel({required Snowflake id, required Map payload, required String? reason}) async { - final response = - await _kernel.dataStore.client.patch('/channels/$id', body: payload, option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + Future updateChannel( + {required Snowflake id, + required Map payload, + required String? reason}) async { + final response = await _kernel.dataStore.client.patch('/channels/$id', + body: payload, + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); final Channel? channel = await serializeChannelResponse(response); @@ -87,21 +104,38 @@ final class ChannelPart implements DataStorePart { } Future deleteChannel(Snowflake id, String? reason) async { - final response = await _kernel.dataStore.client.delete('/channels/$id', option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + final response = await _kernel.dataStore.client.delete('/channels/$id', + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); return switch (response.statusCode) { - int() when status.isSuccess(response.statusCode) => _kernel.marshaller.cache.remove(id.value), - int() when status.isError(response.statusCode) => throw HttpException(response.bodyString), + int() when status.isSuccess(response.statusCode) => + _kernel.marshaller.cache.remove(id.value), + int() when status.isError(response.statusCode) => + throw HttpException(response.bodyString), _ => throw Exception('Unknown status code: ${response.statusCode}'), }; } Future createMessage( - Snowflake? guildId, Snowflake channelId, String? content, List? embeds, Poll? poll, List? components) async { - final response = await _kernel.dataStore.client.post('/channels/$channelId/messages', body: { + Snowflake? guildId, + Snowflake channelId, + String? content, + List? embeds, + Poll? poll, + List? components) async { + final response = await _kernel.dataStore.client + .post('/channels/$channelId/messages', body: { 'content': content, - 'embeds': await Helper.createOrNullAsync(field: embeds, fn: () async => embeds?.map(_kernel.marshaller.serializers.embed.deserialize).toList()), - 'poll': await Helper.createOrNullAsync(field: poll, fn: () async => _kernel.marshaller.serializers.poll.deserialize(poll!)), + 'embeds': await Helper.createOrNullAsync( + field: embeds, + fn: () async => embeds + ?.map(_kernel.marshaller.serializers.embed.deserialize) + .toList()), + 'poll': await Helper.createOrNullAsync( + field: poll, + fn: () async => + _kernel.marshaller.serializers.poll.deserialize(poll!)), 'components': components?.map((e) => e.toJson()).toList(), }); @@ -120,11 +154,14 @@ final class ChannelPart implements DataStorePart { return serializer.serialize(payload); } - Future serializeChannelResponse(Response response) async { + Future serializeChannelResponse( + Response response) async { return switch (response.statusCode) { int() when status.isSuccess(response.statusCode) => () async { - final payload = await _kernel.marshaller.serializers.channels.normalize(response.body); - final channel = await _kernel.marshaller.serializers.channels.serialize(payload); + final payload = await _kernel.marshaller.serializers.channels + .normalize(response.body); + final channel = + await _kernel.marshaller.serializers.channels.serialize(payload); if (channel is ServerChannel) { await _updateCacheFromChannelServer(channel.id, channel, payload); @@ -132,16 +169,21 @@ final class ChannelPart implements DataStorePart { return channel as T?; }, - int() when status.isError(response.statusCode) => throw HttpException(response.bodyString), - _ => throw Exception('Unknown status code: ${response.statusCode} ${response.bodyString}'), + int() when status.isError(response.statusCode) => + throw HttpException(response.bodyString), + _ => throw Exception( + 'Unknown status code: ${response.statusCode} ${response.bodyString}'), } as Future; } - Future _updateCacheFromChannelServer(Snowflake id, ServerChannel channel, Map rawChannel) async { - final server = await _kernel.dataStore.server.getServer(rawChannel['guild_id']); + Future _updateCacheFromChannelServer(Snowflake id, + ServerChannel channel, Map rawChannel) async { + final server = + await _kernel.dataStore.server.getServer(rawChannel['guild_id']); server.channels.list[channel.id] = channel; - final rawServer = await _kernel.marshaller.serializers.server.deserialize(server); + final rawServer = + await _kernel.marshaller.serializers.server.deserialize(server); await _kernel.marshaller.cache.putMany({ _kernel.marshaller.cacheKey.server(server.id): rawServer, diff --git a/lib/infrastructure/internals/datastore/parts/interaction_part.dart b/lib/infrastructure/internals/datastore/parts/interaction_part.dart index 594e08af..b6b4e82f 100644 --- a/lib/infrastructure/internals/datastore/parts/interaction_part.dart +++ b/lib/infrastructure/internals/datastore/parts/interaction_part.dart @@ -15,16 +15,21 @@ final class InteractionPart implements DataStorePart { InteractionPart(this._kernel); - Future replyInteraction(Snowflake id, String token, Map raw) async { - await _kernel.dataStore.client.post('/interactions/$id/$token/callback', body: raw); + Future replyInteraction( + Snowflake id, String token, Map raw) async { + await _kernel.dataStore.client + .post('/interactions/$id/$token/callback', body: raw); } - Future editInteraction(Snowflake botId, String token, Map raw) async { - await _kernel.dataStore.client.patch('/webhooks/$botId/$token/messages/@original', body: raw); + Future editInteraction( + Snowflake botId, String token, Map raw) async { + await _kernel.dataStore.client + .patch('/webhooks/$botId/$token/messages/@original', body: raw); } Future deleteInteraction(Snowflake botId, String token) async { - await _kernel.dataStore.client.delete('/webhooks/$botId/$token/messages/@original'); + await _kernel.dataStore.client + .delete('/webhooks/$botId/$token/messages/@original'); } Future noReplyInteraction(Snowflake id, String token) async { @@ -36,17 +41,21 @@ final class InteractionPart implements DataStorePart { }); } - Future followUpInteraction(Snowflake botId, String token, Map raw) async { + Future followUpInteraction( + Snowflake botId, String token, Map raw) async { await _kernel.dataStore.client.post('/webhooks/$botId/$token', body: raw); } - Future editFollowUpInteraction( - Snowflake botId, String token, Snowflake messageId, Map raw) async { - await _kernel.dataStore.client.patch('/webhooks/$botId/$token/messages/$messageId', body: raw); + Future editFollowUpInteraction(Snowflake botId, String token, + Snowflake messageId, Map raw) async { + await _kernel.dataStore.client + .patch('/webhooks/$botId/$token/messages/$messageId', body: raw); } - Future deleteFollowUpInteraction(Snowflake botId, String token, Snowflake messageId) async { - await _kernel.dataStore.client.delete('/webhooks/$botId/$token/messages/$messageId'); + Future deleteFollowUpInteraction( + Snowflake botId, String token, Snowflake messageId) async { + await _kernel.dataStore.client + .delete('/webhooks/$botId/$token/messages/$messageId'); } Future waitInteraction(Snowflake id, String token) async { @@ -58,17 +67,22 @@ final class InteractionPart implements DataStorePart { }); } - Future editWaitInteraction( - Snowflake botId, String token, Snowflake messageId, Map raw) async { - await _kernel.dataStore.client.patch('/webhooks/$botId/$token/messages/$messageId', body: raw); + Future editWaitInteraction(Snowflake botId, String token, + Snowflake messageId, Map raw) async { + await _kernel.dataStore.client + .patch('/webhooks/$botId/$token/messages/$messageId', body: raw); } - Future deleteWaitInteraction(Snowflake botId, String token, Snowflake messageId) async { - await _kernel.dataStore.client.delete('/webhooks/$botId/$token/messages/$messageId'); + Future deleteWaitInteraction( + Snowflake botId, String token, Snowflake messageId) async { + await _kernel.dataStore.client + .delete('/webhooks/$botId/$token/messages/$messageId'); } - Future sendDialog(Snowflake id, String token, DialogBuilder dialog) async { - await _kernel.dataStore.client.post('/interactions/$id/$token/callback', body: { + Future sendDialog( + Snowflake id, String token, DialogBuilder dialog) async { + await _kernel.dataStore.client + .post('/interactions/$id/$token/callback', body: { 'type': InteractionCallbackType.modal.value, 'data': dialog.toJson(), }); diff --git a/lib/infrastructure/internals/datastore/parts/member_part.dart b/lib/infrastructure/internals/datastore/parts/member_part.dart index c27e9ede..90b4cf55 100644 --- a/lib/infrastructure/internals/datastore/parts/member_part.dart +++ b/lib/infrastructure/internals/datastore/parts/member_part.dart @@ -16,17 +16,20 @@ final class MemberPart implements DataStorePart { MemberPart(this._kernel); - Future getMember({required Snowflake serverId, required Snowflake memberId}) async { + Future getMember( + {required Snowflake serverId, required Snowflake memberId}) async { final cacheKeys = _kernel.marshaller.cacheKey; final memberCacheKey = cacheKeys.member(serverId, memberId); - Map? cachedRawMember = await _kernel.marshaller.cache.get(memberCacheKey); + Map? cachedRawMember = + await _kernel.marshaller.cache.get(memberCacheKey); if (cachedRawMember != null) { return _kernel.marshaller.serializers.member.serialize(cachedRawMember); } - final response = await _kernel.dataStore.client.get('/guilds/$serverId/members/$memberId'); + final response = await _kernel.dataStore.client + .get('/guilds/$serverId/members/$memberId'); if (status.isError(response.statusCode)) { throw HttpException(response.body); } @@ -38,19 +41,23 @@ final class MemberPart implements DataStorePart { return _kernel.marshaller.serializers.member.serialize(cachedRawMember); } - Future> getMembers(Snowflake guildId, {bool force = false}) async { + Future> getMembers(Snowflake guildId, + {bool force = false}) async { final serverCacheKey = _kernel.marshaller.cacheKey.server(guildId); final rawServer = await _kernel.marshaller.cache.getOrFail(serverCacheKey); final rawMemberIds = List.from(rawServer['members']); - final rawCachedMembers = await _kernel.marshaller.cache.getMany(rawMemberIds); + final rawCachedMembers = + await _kernel.marshaller.cache.getMany(rawMemberIds); if (rawMemberIds.length == rawCachedMembers.length) { return Future.wait(rawCachedMembers.nonNulls - .map((element) async => _kernel.marshaller.serializers.member.serialize(element)) + .map((element) async => + _kernel.marshaller.serializers.member.serialize(element)) .toList()); } - final response = await _kernel.dataStore.client.get('/guilds/$guildId/members'); + final response = + await _kernel.dataStore.client.get('/guilds/$guildId/members'); if (status.isError(response.statusCode)) { throw HttpException(response.body); } @@ -66,15 +73,18 @@ final class MemberPart implements DataStorePart { required Snowflake memberId, required Map payload, required String? reason}) async { - final response = await _kernel.dataStore.client.patch('/guilds/$serverId/members/$memberId', + final response = await _kernel.dataStore.client.patch( + '/guilds/$serverId/members/$memberId', body: payload, - option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); if (status.isError(response.statusCode)) { throw HttpException(response.body); } - final rawMember = await _kernel.marshaller.serializers.member.normalize(response.body); + final rawMember = + await _kernel.marshaller.serializers.member.normalize(response.body); return _kernel.marshaller.serializers.member.serialize(rawMember); } @@ -83,9 +93,11 @@ final class MemberPart implements DataStorePart { required Duration? deleteSince, required Snowflake memberId, String? reason}) async { - final response = await _kernel.dataStore.client.put('/guilds/$serverId/bans/$memberId', + final response = await _kernel.dataStore.client.put( + '/guilds/$serverId/bans/$memberId', body: {'delete_message_seconds': deleteSince?.inSeconds}, - option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); if (status.isSuccess(response.statusCode)) { return; @@ -93,9 +105,13 @@ final class MemberPart implements DataStorePart { } Future kickMember( - {required Snowflake serverId, required Snowflake memberId, String? reason}) async { - final response = await _kernel.dataStore.client.delete('/guilds/$serverId/members/$memberId', - option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + {required Snowflake serverId, + required Snowflake memberId, + String? reason}) async { + final response = await _kernel.dataStore.client.delete( + '/guilds/$serverId/members/$memberId', + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); if (status.isSuccess(response.statusCode)) { return; diff --git a/lib/infrastructure/internals/datastore/parts/message_part.dart b/lib/infrastructure/internals/datastore/parts/message_part.dart index 975f6496..48f6083a 100644 --- a/lib/infrastructure/internals/datastore/parts/message_part.dart +++ b/lib/infrastructure/internals/datastore/parts/message_part.dart @@ -18,32 +18,38 @@ final class MessagePart implements DataStorePart { Future getServerMessage( {required Snowflake messageId, required Snowflake channelId}) async { - final messageCacheKey = _kernel.marshaller.cacheKey.message(channelId, channelId); + final messageCacheKey = + _kernel.marshaller.cacheKey.message(channelId, channelId); final channelCacheKey = _kernel.marshaller.cacheKey.channel(channelId); final rawMessage = await _kernel.marshaller.cache.get(messageCacheKey); - final rawChannel = await _kernel.marshaller.cache.getOrFail(channelCacheKey); - final serverChannel = - await _kernel.marshaller.serializers.channels.serialize(rawChannel) as ServerChannel; + final rawChannel = + await _kernel.marshaller.cache.getOrFail(channelCacheKey); + final serverChannel = await _kernel.marshaller.serializers.channels + .serialize(rawChannel) as ServerChannel; if (rawMessage != null) { - final message = await _kernel.marshaller.serializers.serverMessage.serialize(rawMessage) + final message = await _kernel.marshaller.serializers.serverMessage + .serialize(rawMessage) ..channel = serverChannel; return message; } - final response = await _kernel.dataStore.client.get('/channels/$channelId/messages/$messageId'); + final response = await _kernel.dataStore.client + .get('/channels/$channelId/messages/$messageId'); if (status.isError(response.statusCode)) { throw HttpException(response.body); } - final payload = await _kernel.marshaller.serializers.serverMessage.normalize({ + final payload = + await _kernel.marshaller.serializers.serverMessage.normalize({ ...response.body, 'server_id': serverChannel.serverId.value, }); - final serverMessage = await _kernel.marshaller.serializers.serverMessage.serialize(payload); + final serverMessage = + await _kernel.marshaller.serializers.serverMessage.serialize(payload); serverMessage.channel = serverChannel; return serverMessage; @@ -51,24 +57,31 @@ final class MessagePart implements DataStorePart { Future getPrivateMessage( {required Snowflake messageId, required Snowflake channelId}) async { - final messageCacheKey = _kernel.marshaller.cacheKey.message(channelId, channelId); + final messageCacheKey = + _kernel.marshaller.cacheKey.message(channelId, channelId); final channelCacheKey = _kernel.marshaller.cacheKey.channel(channelId); final rawMessage = await _kernel.marshaller.cache.get(messageCacheKey); - final rawChannel = await _kernel.marshaller.cache.getOrFail(channelCacheKey); - final channel = await _kernel.marshaller.serializers.channels.serialize(rawChannel) as PrivateChannel; + final rawChannel = + await _kernel.marshaller.cache.getOrFail(channelCacheKey); + final channel = await _kernel.marshaller.serializers.channels + .serialize(rawChannel) as PrivateChannel; if (rawMessage != null) { - final message = await _kernel.marshaller.serializers.privateMessage.serialize(rawMessage) + final message = await _kernel.marshaller.serializers.privateMessage + .serialize(rawMessage) ..channel = channel; return message; } - final response = await _kernel.dataStore.client.get('/channels/$channelId/messages/$messageId'); + final response = await _kernel.dataStore.client + .get('/channels/$channelId/messages/$messageId'); - final payload = await _kernel.marshaller.serializers.serverMessage.normalize(response.body); - final privateMessage = await _kernel.marshaller.serializers.privateMessage.serialize(payload); + final payload = await _kernel.marshaller.serializers.serverMessage + .normalize(response.body); + final privateMessage = + await _kernel.marshaller.serializers.privateMessage.serialize(payload); privateMessage.channel = channel; return privateMessage; diff --git a/lib/infrastructure/internals/datastore/parts/role_part.dart b/lib/infrastructure/internals/datastore/parts/role_part.dart index 6457cb2f..6088c940 100644 --- a/lib/infrastructure/internals/datastore/parts/role_part.dart +++ b/lib/infrastructure/internals/datastore/parts/role_part.dart @@ -16,7 +16,8 @@ final class RolePart implements DataStorePart { RolePart(this._kernel); - Future getRole({required Snowflake serverId, required Snowflake roleId}) async { + Future getRole( + {required Snowflake serverId, required Snowflake roleId}) async { final cacheKey = _kernel.marshaller.cacheKey.serverRole(serverId, roleId); final rawRole = await _kernel.marshaller.cache.get(cacheKey); @@ -24,12 +25,14 @@ final class RolePart implements DataStorePart { return _kernel.marshaller.serializers.role.serialize(rawRole); } - final response = await _kernel.dataStore.client.get('/guilds/$serverId/roles/$roleId'); + final response = + await _kernel.dataStore.client.get('/guilds/$serverId/roles/$roleId'); if (status.isError(response.statusCode)) { throw HttpException(response.body); } - final payload = await _kernel.marshaller.serializers.role.normalize(response.body); + final payload = + await _kernel.marshaller.serializers.role.normalize(response.body); return _kernel.marshaller.serializers.role.serialize(payload); } @@ -38,8 +41,10 @@ final class RolePart implements DataStorePart { required Snowflake serverId, required Snowflake roleId, required String? reason}) async { - await _kernel.dataStore.client.put('/guilds/$serverId/members/$memberId/roles/$roleId', - option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + await _kernel.dataStore.client.put( + '/guilds/$serverId/members/$memberId/roles/$roleId', + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); } Future removeRole( @@ -47,8 +52,10 @@ final class RolePart implements DataStorePart { required Snowflake serverId, required Snowflake roleId, required String? reason}) async { - await _kernel.dataStore.client.delete('/guilds/$serverId/members/$memberId/roles/$roleId', - option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + await _kernel.dataStore.client.delete( + '/guilds/$serverId/members/$memberId/roles/$roleId', + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); } Future syncRoles( @@ -58,7 +65,8 @@ final class RolePart implements DataStorePart { required String? reason}) async { await _kernel.dataStore.client.patch('/guilds/$serverId/members/$memberId', body: {'roles': roleIds}, - option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); } Future updateRole( @@ -66,21 +74,27 @@ final class RolePart implements DataStorePart { required Snowflake serverId, required Map payload, required String? reason}) async { - final response = await _kernel.dataStore.client.patch('/guilds/$serverId/roles/$id', + final response = await _kernel.dataStore.client.patch( + '/guilds/$serverId/roles/$id', body: payload, - option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); if (status.isError(response.statusCode)) { throw HttpException(response.body); } - final body = await _kernel.marshaller.serializers.role.normalize(response.body); + final body = + await _kernel.marshaller.serializers.role.normalize(response.body); return _kernel.marshaller.serializers.role.serialize(body); } Future deleteRole( - {required Snowflake id, required Snowflake guildId, required String? reason}) async { + {required Snowflake id, + required Snowflake guildId, + required String? reason}) async { await _kernel.dataStore.client.delete('/guilds/$guildId/roles/$id', - option: HttpRequestOptionImpl(headers: {DiscordHeader.auditLogReason(reason)})); + option: HttpRequestOptionImpl( + headers: {DiscordHeader.auditLogReason(reason)})); } } diff --git a/lib/infrastructure/internals/datastore/parts/server_part.dart b/lib/infrastructure/internals/datastore/parts/server_part.dart index 08a6c218..b9000b5a 100644 --- a/lib/infrastructure/internals/datastore/parts/server_part.dart +++ b/lib/infrastructure/internals/datastore/parts/server_part.dart @@ -30,7 +30,8 @@ final class ServerPart implements DataStorePart { await getChannels(id); await _kernel.dataStore.member.getMembers(id); - final payload = await _kernel.marshaller.serializers.server.normalize(serverResponse.body); + final payload = await _kernel.marshaller.serializers.server + .normalize(serverResponse.body); return _kernel.marshaller.serializers.server.serialize(payload); } @@ -41,35 +42,42 @@ final class ServerPart implements DataStorePart { } return Future.wait(List.from(response.body).map((element) async { - final channel = await _kernel.marshaller.serializers.channels.normalize(element); - return _kernel.marshaller.serializers.channels.serialize(channel) as Future; + final channel = + await _kernel.marshaller.serializers.channels.normalize(element); + return _kernel.marshaller.serializers.channels.serialize(channel) + as Future; }).toList()); } Future getRole(Snowflake serverId, Snowflake roleId) async { - final roleCacheKey = _kernel.marshaller.cacheKey.serverRole(serverId, roleId); + final roleCacheKey = + _kernel.marshaller.cacheKey.serverRole(serverId, roleId); final cachedRawRole = await _kernel.marshaller.cache.get(roleCacheKey); if (cachedRawRole != null) { return _kernel.marshaller.serializers.role.serialize(cachedRawRole); } - final response = await _kernel.dataStore.client.get('/guilds/$serverId/roles/$roleId'); + final response = + await _kernel.dataStore.client.get('/guilds/$serverId/roles/$roleId'); if (status.isError(response.statusCode)) { throw HttpException(response.body); } - final rolePayload = await _kernel.marshaller.serializers.role.normalize(response.body); + final rolePayload = + await _kernel.marshaller.serializers.role.normalize(response.body); return _kernel.marshaller.serializers.role.serialize(rolePayload); } Future> getRoles(Snowflake guildId, {bool force = false}) async { - final response = await _kernel.dataStore.client.get('/guilds/$guildId/roles'); + final response = + await _kernel.dataStore.client.get('/guilds/$guildId/roles'); if (status.isError(response.statusCode)) { throw HttpException(response.body); } return Future.wait(List.from(response.body).map((element) async { - final payload = await _kernel.marshaller.serializers.role.normalize(element); + final payload = + await _kernel.marshaller.serializers.role.normalize(element); return _kernel.marshaller.serializers.role.serialize(payload); }).toList()); } diff --git a/lib/infrastructure/internals/datastore/parts/sticker_part.dart b/lib/infrastructure/internals/datastore/parts/sticker_part.dart index 51d7a9c6..c1d02855 100644 --- a/lib/infrastructure/internals/datastore/parts/sticker_part.dart +++ b/lib/infrastructure/internals/datastore/parts/sticker_part.dart @@ -15,20 +15,24 @@ final class StickerPart implements DataStorePart { StickerPart(this._kernel); Future getSticker(Snowflake serverId, Snowflake stickerId) async { - final stickerCacheKey = _kernel.marshaller.cacheKey.sticker(serverId, stickerId); + final stickerCacheKey = + _kernel.marshaller.cacheKey.sticker(serverId, stickerId); - final Map? cachedRawSticker = await _kernel.marshaller.cache.get(stickerCacheKey); + final Map? cachedRawSticker = + await _kernel.marshaller.cache.get(stickerCacheKey); if (cachedRawSticker != null) { return _kernel.marshaller.serializers.sticker.serialize(cachedRawSticker); } - final response = await _kernel.dataStore.client.get('/guilds/$serverId/stickers/$stickerId}'); + final response = await _kernel.dataStore.client + .get('/guilds/$serverId/stickers/$stickerId}'); if (status.isError(response.statusCode)) { throw HttpException(response.body); } - final payload = await _kernel.marshaller.serializers.sticker.normalize(response.body); + final payload = + await _kernel.marshaller.serializers.sticker.normalize(response.body); return _kernel.marshaller.serializers.sticker.serialize(payload); } } diff --git a/lib/infrastructure/internals/datastore/parts/user_part.dart b/lib/infrastructure/internals/datastore/parts/user_part.dart index bd6c986d..7d4d5c6f 100644 --- a/lib/infrastructure/internals/datastore/parts/user_part.dart +++ b/lib/infrastructure/internals/datastore/parts/user_part.dart @@ -26,7 +26,8 @@ final class UserPart implements DataStorePart { throw HttpException(response.body); } - final payload = await _kernel.marshaller.serializers.user.normalize(response.body); + final payload = + await _kernel.marshaller.serializers.user.normalize(response.body); return _kernel.marshaller.serializers.user.serialize(payload); } } diff --git a/lib/infrastructure/internals/environment/environment.dart b/lib/infrastructure/internals/environment/environment.dart index a66a9ce3..d4fd61de 100644 --- a/lib/infrastructure/internals/environment/environment.dart +++ b/lib/infrastructure/internals/environment/environment.dart @@ -24,13 +24,15 @@ final class Environment implements EnvContract { T getRawOrFail(String key) { return _values.entries .firstWhere((element) => element.key == key, - orElse: () => throw Exception('Environment variable $key not found')) + orElse: () => + throw Exception('Environment variable $key not found')) .value as T; } @override T get(EnvSchema variable) { - final result = _values.entries.firstWhereOrNull((element) => element.key == variable.key); + final result = _values.entries + .firstWhereOrNull((element) => element.key == variable.key); if (variable.required && result == null) { throw Exception('Environment variable ${variable.key} not found'); @@ -51,7 +53,8 @@ final class Environment implements EnvContract { final elements = dir.listSync(); final environments = elements - .where((element) => element is File && element.uri.pathSegments.last.contains('.env')) + .where((element) => + element is File && element.uri.pathSegments.last.contains('.env')) .toList(); final orderedFiles = orderEnvFiles(environments); @@ -59,7 +62,8 @@ final class Environment implements EnvContract { final environment = orderedFiles.first; final lines = File.fromUri(environment.uri).readAsLinesSync(); - for (final line in lines.nonNulls.where((element) => element.isNotEmpty)) { + for (final line + in lines.nonNulls.where((element) => element.isNotEmpty)) { final [key, value] = line.split('='); _values[key] = value; } diff --git a/lib/infrastructure/internals/hmr/entities/directory_watcher_element.dart b/lib/infrastructure/internals/hmr/entities/directory_watcher_element.dart index 20d4afca..78e6cdb5 100644 --- a/lib/infrastructure/internals/hmr/entities/directory_watcher_element.dart +++ b/lib/infrastructure/internals/hmr/entities/directory_watcher_element.dart @@ -12,13 +12,12 @@ final class DirectoryWatcherElement implements WatcherElement { final void Function(WatchEvent event) editFile; final void Function(WatchEvent event) removeFile; - DirectoryWatcherElement({ - required this.appRoot, - required this.watcherRoot, - required this.addFile, - required this.editFile, - required this.removeFile - }) { + DirectoryWatcherElement( + {required this.appRoot, + required this.watcherRoot, + required this.addFile, + required this.editFile, + required this.removeFile}) { _watcher = DirectoryWatcher(watcherRoot.path); } @@ -28,7 +27,7 @@ final class DirectoryWatcherElement implements WatcherElement { } @override - void dispatch (WatchEvent event) { + void dispatch(WatchEvent event) { return switch (event.type) { ChangeType.ADD => addFile(event), ChangeType.MODIFY => editFile(event), diff --git a/lib/infrastructure/internals/hmr/entities/file_watcher_element.dart b/lib/infrastructure/internals/hmr/entities/file_watcher_element.dart index 4864f6eb..9070ec6f 100644 --- a/lib/infrastructure/internals/hmr/entities/file_watcher_element.dart +++ b/lib/infrastructure/internals/hmr/entities/file_watcher_element.dart @@ -12,13 +12,12 @@ final class FileWatcherElement implements WatcherElement { final void Function(WatchEvent event) editFile; final void Function(WatchEvent event) removeFile; - FileWatcherElement({ - required this.appRoot, - required this.watchedFile, - required this.addFile, - required this.editFile, - required this.removeFile - }) { + FileWatcherElement( + {required this.appRoot, + required this.watchedFile, + required this.addFile, + required this.editFile, + required this.removeFile}) { _watcher = FileWatcher(watchedFile.path); } @@ -28,7 +27,7 @@ final class FileWatcherElement implements WatcherElement { } @override - void dispatch (WatchEvent event) { + void dispatch(WatchEvent event) { return switch (event.type) { ChangeType.ADD => addFile(event), ChangeType.MODIFY => editFile(event), diff --git a/lib/infrastructure/internals/hmr/entities/watcher_element.dart b/lib/infrastructure/internals/hmr/entities/watcher_element.dart index c39aee20..ab343402 100644 --- a/lib/infrastructure/internals/hmr/entities/watcher_element.dart +++ b/lib/infrastructure/internals/hmr/entities/watcher_element.dart @@ -2,5 +2,5 @@ import 'package:watcher/watcher.dart'; abstract interface class WatcherElement { void watch(); - void dispatch (WatchEvent event); + void dispatch(WatchEvent event); } diff --git a/lib/infrastructure/internals/hmr/hot_module_reloading.dart b/lib/infrastructure/internals/hmr/hot_module_reloading.dart index 02d0671d..08d76b0e 100644 --- a/lib/infrastructure/internals/hmr/hot_module_reloading.dart +++ b/lib/infrastructure/internals/hmr/hot_module_reloading.dart @@ -28,8 +28,8 @@ final class HotModuleReloading { final Map _shards; final Function() _createShards; - HotModuleReloading( - this._devPort, this._watcherConfig, this._kernel, this._createShards, this._shards); + HotModuleReloading(this._devPort, this._watcherConfig, this._kernel, + this._createShards, this._shards); Future spawn() async { if (Isolate.current.debugName == 'dev') { @@ -39,7 +39,8 @@ final class HotModuleReloading { _devPort!.send(port.sendPort); await _kernel.marshaller.cache.init(); await for (final Map message in stream) { - _kernel.packetListener.dispatcher.dispatch(ShardMessageImpl.of(message)); + _kernel.packetListener.dispatcher + .dispatch(ShardMessageImpl.of(message)); } } else { _createHotModuleLoader(); @@ -66,7 +67,8 @@ final class HotModuleReloading { void _createDevelopmentIsolate() { final port = ReceivePort(); - final uri = Uri.parse(path.join(Directory.current.path, 'src', 'main.dart')); + final uri = + Uri.parse(path.join(Directory.current.path, 'src', 'main.dart')); Isolate.spawnUri(Uri.file(uri.path), [], port.sendPort, debugName: 'dev') .then((Isolate isolate) async { @@ -74,7 +76,8 @@ final class HotModuleReloading { devSendPort = await port.first; _shards.forEach((key, value) { - final Queue> queue = Queue.from(value.onceEventQueue); + final Queue> queue = + Queue.from(value.onceEventQueue); while (queue.isNotEmpty) { final response = queue.removeFirst(); devSendPort?.send(response); @@ -90,7 +93,8 @@ final class HotModuleReloading { } } - final String location = event.path.replaceFirst(Directory.current.path, '').substring(1); + final String location = + event.path.replaceFirst(Directory.current.path, '').substring(1); if (fileLocation == location) { fileRefreshCount++; @@ -100,17 +104,17 @@ final class HotModuleReloading { } List formatMessage(String action) => [ - SetStyles(Style.foreground(Logger.primaryColor)), - Print('hmr $action '), - SetStyles.reset, - SetStyles(Style.foreground(Logger.mutedColor)), - Print(location), - SetStyles.reset, - SetStyles(Style.foreground(Color.yellow)), - Print(' (x$fileRefreshCount)'), - SetStyles.reset, - AsciiControl.lineFeed, - ]; + SetStyles(Style.foreground(Logger.primaryColor)), + Print('hmr $action '), + SetStyles.reset, + SetStyles(Style.foreground(Logger.mutedColor)), + Print(location), + SetStyles.reset, + SetStyles(Style.foreground(Color.yellow)), + Print(' (x$fileRefreshCount)'), + SetStyles.reset, + AsciiControl.lineFeed, + ]; final message = switch (event.type) { ChangeType.ADD => formatMessage('create'), diff --git a/lib/infrastructure/internals/hmr/watcher.dart b/lib/infrastructure/internals/hmr/watcher.dart index 8e2a496d..1cc2bf7b 100644 --- a/lib/infrastructure/internals/hmr/watcher.dart +++ b/lib/infrastructure/internals/hmr/watcher.dart @@ -11,26 +11,25 @@ final class Watcher { final bool allowReload; void Function(WatchEvent event) onReload; - Watcher({ required this.allowReload, required this.appRoot, required List folders, required List files, required this.onReload }) { + Watcher( + {required this.allowReload, + required this.appRoot, + required List folders, + required List files, + required this.onReload}) { watchers.addAll(List.from([ - ...folders.map((folder) => - DirectoryWatcherElement( - appRoot: appRoot, - watcherRoot: folder, - addFile: onReload, - editFile: onReload, - removeFile: onReload - ) - ), - ...files.map((file) => - FileWatcherElement( - appRoot: appRoot, - watchedFile: file, - addFile: onReload, - editFile: onReload, - removeFile: onReload - ) - ) + ...folders.map((folder) => DirectoryWatcherElement( + appRoot: appRoot, + watcherRoot: folder, + addFile: onReload, + editFile: onReload, + removeFile: onReload)), + ...files.map((file) => FileWatcherElement( + appRoot: appRoot, + watchedFile: file, + addFile: onReload, + editFile: onReload, + removeFile: onReload)) ])); } diff --git a/lib/infrastructure/internals/hmr/watcher_builder.dart b/lib/infrastructure/internals/hmr/watcher_builder.dart index 69450a86..85852e85 100644 --- a/lib/infrastructure/internals/hmr/watcher_builder.dart +++ b/lib/infrastructure/internals/hmr/watcher_builder.dart @@ -13,31 +13,30 @@ final class WatcherBuilder { WatcherBuilder(this._appRoot); - WatcherBuilder setAllowReload (bool value) { + WatcherBuilder setAllowReload(bool value) { _allowReload = value; return this; } - WatcherBuilder addWatchFolder (Directory value) { + WatcherBuilder addWatchFolder(Directory value) { _folderWatchers.add(value); return this; } - WatcherBuilder addWatchFile (File value) { + WatcherBuilder addWatchFile(File value) { _fileWatchers.add(value); return this; } - WatcherBuilder onReload (Function(watcher.WatchEvent) callback) { + WatcherBuilder onReload(Function(watcher.WatchEvent) callback) { _onReload = callback; return this; } - Watcher build () => Watcher( + Watcher build() => Watcher( allowReload: _allowReload, appRoot: _appRoot, folders: _folderWatchers, files: _fileWatchers, - onReload: _onReload - ); + onReload: _onReload); } diff --git a/lib/infrastructure/internals/http/discord_header.dart b/lib/infrastructure/internals/http/discord_header.dart index 5aef8b0c..a308c35a 100644 --- a/lib/infrastructure/internals/http/discord_header.dart +++ b/lib/infrastructure/internals/http/discord_header.dart @@ -13,5 +13,6 @@ final class DiscordHeader implements Header { DiscordHeader.accept(String value) : this('Accept', value); DiscordHeader.authorization(String value) : this('Authorization', value); DiscordHeader.userAgent(String value) : this('User-Agent', value); - DiscordHeader.auditLogReason(String? value) : this('X-Audit-Log-Reason', value ?? ''); + DiscordHeader.auditLogReason(String? value) + : this('X-Audit-Log-Reason', value ?? ''); } diff --git a/lib/infrastructure/internals/http/http_endpoint.dart b/lib/infrastructure/internals/http/http_endpoint.dart index 73243863..36b8332a 100644 --- a/lib/infrastructure/internals/http/http_endpoint.dart +++ b/lib/infrastructure/internals/http/http_endpoint.dart @@ -7,7 +7,8 @@ class HttpEndpoint { factory HttpEndpoint.getServerChannelList({required String guildId}) => HttpEndpoint('GET', '/guilds/$guildId/channels'); - factory HttpEndpoint.getServerChannel({required String guildId, required String channelId}) => + factory HttpEndpoint.getServerChannel( + {required String guildId, required String channelId}) => HttpEndpoint('GET', '/guilds/$guildId/channels/$channelId'); @override diff --git a/lib/infrastructure/internals/http/request_executor.dart b/lib/infrastructure/internals/http/request_executor.dart index 0794eb6d..ca8914bf 100644 --- a/lib/infrastructure/internals/http/request_executor.dart +++ b/lib/infrastructure/internals/http/request_executor.dart @@ -24,13 +24,14 @@ final class RequestExecutor implements RequestExecutorContract { Future send(HttpEndpoint endpoint, {List? values}) async { final response = await client.send(endpoint.method, endpoint.url); - return switch(response.statusCode) { - _ when [404, 401, 500].contains(response.statusCode) => throwError(response), + return switch (response.statusCode) { + _ when [404, 401, 500].contains(response.statusCode) => + throwError(response), _ => response.body } as T; } - void throwError (Response response, { String? message }) { + void throwError(Response response, {String? message}) { final data = { 'method': response.method, 'statusCode': response.statusCode, diff --git a/lib/infrastructure/internals/interactions/interaction.dart b/lib/infrastructure/internals/interactions/interaction.dart index dda812c5..36faebeb 100644 --- a/lib/infrastructure/internals/interactions/interaction.dart +++ b/lib/infrastructure/internals/interactions/interaction.dart @@ -34,10 +34,14 @@ final class Interaction implements InteractionContract { 'content': content, 'embeds': await Helper.createOrNullAsync( field: embeds, - fn: () async => embeds.map(_marshaller.serializers.embed.deserialize).toList()), + fn: () async => + embeds.map(_marshaller.serializers.embed.deserialize).toList()), 'components': Helper.createOrNull( - field: components.isNotEmpty, fn: () => components.map((e) => e.toJson()).toList()), - 'flags': ephemeral ? MessageFlagType.ephemeral.value : MessageFlagType.none.value, + field: components.isNotEmpty, + fn: () => components.map((e) => e.toJson()).toList()), + 'flags': ephemeral + ? MessageFlagType.ephemeral.value + : MessageFlagType.none.value, } }); @@ -53,9 +57,11 @@ final class Interaction implements InteractionContract { 'content': content, 'embeds': await Helper.createOrNullAsync( field: embeds, - fn: () async => embeds.map(_marshaller.serializers.embed.deserialize).toList()), + fn: () async => + embeds.map(_marshaller.serializers.embed.deserialize).toList()), 'components': Helper.createOrNull( - field: components.isNotEmpty, fn: () => components.map((e) => e.toJson()).toList()), + field: components.isNotEmpty, + fn: () => components.map((e) => e.toJson()).toList()), }); return this; } @@ -80,10 +86,14 @@ final class Interaction implements InteractionContract { 'content': content, 'embeds': await Helper.createOrNullAsync( field: embeds, - fn: () async => embeds.map(_marshaller.serializers.embed.deserialize).toList()), + fn: () async => + embeds.map(_marshaller.serializers.embed.deserialize).toList()), 'components': Helper.createOrNull( - field: components.isNotEmpty, fn: () => components.map((e) => e.toJson()).toList()), - 'flags': ephemeral ? MessageFlagType.ephemeral.value : MessageFlagType.none.value, + field: components.isNotEmpty, + fn: () => components.map((e) => e.toJson()).toList()), + 'flags': ephemeral + ? MessageFlagType.ephemeral.value + : MessageFlagType.none.value, }); return this; } @@ -98,9 +108,11 @@ final class Interaction implements InteractionContract { 'content': content, 'embeds': await Helper.createOrNullAsync( field: embeds, - fn: () async => embeds.map(_marshaller.serializers.embed.deserialize).toList()), + fn: () async => + embeds.map(_marshaller.serializers.embed.deserialize).toList()), 'components': Helper.createOrNull( - field: components.isNotEmpty, fn: () => components.map((e) => e.toJson()).toList()), + field: components.isNotEmpty, + fn: () => components.map((e) => e.toJson()).toList()), }); return this; } @@ -126,9 +138,11 @@ final class Interaction implements InteractionContract { 'content': content, 'embeds': await Helper.createOrNullAsync( field: embeds, - fn: () async => embeds.map(_marshaller.serializers.embed.deserialize).toList()), + fn: () async => + embeds.map(_marshaller.serializers.embed.deserialize).toList()), 'components': Helper.createOrNull( - field: components.isNotEmpty, fn: () => components.map((e) => e.toJson()).toList()), + field: components.isNotEmpty, + fn: () => components.map((e) => e.toJson()).toList()), }); return this; } diff --git a/lib/infrastructure/internals/interactions/types/interaction_callback_type.dart b/lib/infrastructure/internals/interactions/types/interaction_callback_type.dart index cbf4abb2..88342805 100644 --- a/lib/infrastructure/internals/interactions/types/interaction_callback_type.dart +++ b/lib/infrastructure/internals/interactions/types/interaction_callback_type.dart @@ -10,4 +10,4 @@ enum InteractionCallbackType { final int value; const InteractionCallbackType(this.value); -} \ No newline at end of file +} diff --git a/lib/infrastructure/internals/interactions/types/interaction_contract.dart b/lib/infrastructure/internals/interactions/types/interaction_contract.dart index 0c4fb0d3..a969d82e 100644 --- a/lib/infrastructure/internals/interactions/types/interaction_contract.dart +++ b/lib/infrastructure/internals/interactions/types/interaction_contract.dart @@ -21,7 +21,9 @@ abstract class InteractionContract { /// ```dart /// final interaction = await interaction.editReply(content: 'New Hello Mineral'); Future editReply( - {String content, List embeds, List components}); + {String content, + List embeds, + List components}); /// Use to delete the reply to the interaction. Need a reply to delete. /// Usage: diff --git a/lib/infrastructure/internals/marshaller/cache_key.dart b/lib/infrastructure/internals/marshaller/cache_key.dart index 005a38db..20e97127 100644 --- a/lib/infrastructure/internals/marshaller/cache_key.dart +++ b/lib/infrastructure/internals/marshaller/cache_key.dart @@ -35,7 +35,8 @@ final class CacheKey { return ref ? 'ref:$key' : key; } - String memberAssets(Snowflake serverId, Snowflake memberId, {bool ref = false}) { + String memberAssets(Snowflake serverId, Snowflake memberId, + {bool ref = false}) { final key = '${member(serverId, memberId)}/assets'; return ref ? 'ref:$key' : key; } @@ -50,7 +51,8 @@ final class CacheKey { return ref ? 'ref:$key' : key; } - String serverEmoji(Snowflake serverId, Snowflake emojiId, {bool ref = false}) { + String serverEmoji(Snowflake serverId, Snowflake emojiId, + {bool ref = false}) { final key = '${server(serverId)}/emojis/$emojiId'; return ref ? 'ref:$key' : key; } @@ -67,6 +69,5 @@ final class CacheKey { String sticker(Snowflake serverId, Snowflake stickerId) => '${server(serverId)}/stickers/$stickerId'; - String thread(Snowflake threadId) => - 'threads/$threadId'; + String thread(Snowflake threadId) => 'threads/$threadId'; } diff --git a/lib/infrastructure/internals/marshaller/factories/channels/private_channel_factory.dart b/lib/infrastructure/internals/marshaller/factories/channels/private_channel_factory.dart index 1c5d3949..9a75f1e0 100644 --- a/lib/infrastructure/internals/marshaller/factories/channels/private_channel_factory.dart +++ b/lib/infrastructure/internals/marshaller/factories/channels/private_channel_factory.dart @@ -4,18 +4,21 @@ import 'package:mineral/api/private/channels/private_channel.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/channel_factory.dart'; -final class PrivateChannelFactory implements ChannelFactoryContract { +final class PrivateChannelFactory + implements ChannelFactoryContract { @override ChannelType get type => ChannelType.dm; @override - Future serialize(MarshallerContract marshaller, Map json) async { + Future serialize( + MarshallerContract marshaller, Map json) async { final properties = await ChannelProperties.serializeCache(marshaller, json); return PrivateChannel(properties); } @override - Future> normalize(MarshallerContract marshaller, Map json) async { + Future> normalize( + MarshallerContract marshaller, Map json) async { final payload = { 'id': json['id'], 'type': json['type'], @@ -33,7 +36,8 @@ final class PrivateChannelFactory implements ChannelFactoryContract deserialize(MarshallerContract marshaller, PrivateChannel channel) { + Map deserialize( + MarshallerContract marshaller, PrivateChannel channel) { return { 'id': channel.id.value, 'type': channel.type.value, diff --git a/lib/infrastructure/internals/marshaller/factories/channels/server_announcement_channel_factory.dart b/lib/infrastructure/internals/marshaller/factories/channels/server_announcement_channel_factory.dart index 4065ee1a..71844640 100644 --- a/lib/infrastructure/internals/marshaller/factories/channels/server_announcement_channel_factory.dart +++ b/lib/infrastructure/internals/marshaller/factories/channels/server_announcement_channel_factory.dart @@ -6,12 +6,14 @@ import 'package:mineral/api/server/channels/server_announcement_channel.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/channel_factory.dart'; -final class ServerAnnouncementChannelFactory implements ChannelFactoryContract { +final class ServerAnnouncementChannelFactory + implements ChannelFactoryContract { @override ChannelType get type => ChannelType.guildAnnouncement; @override - Future> normalize(MarshallerContract marshaller, Map json) async { + Future> normalize( + MarshallerContract marshaller, Map json) async { final payload = { 'id': json['id'], 'type': json['type'], @@ -31,14 +33,18 @@ final class ServerAnnouncementChannelFactory implements ChannelFactoryContract serialize(MarshallerContract marshaller, Map json) async { + Future serialize( + MarshallerContract marshaller, Map json) async { final properties = await ChannelProperties.serializeCache(marshaller, json); return ServerAnnouncementChannel(properties); } @override - Future> deserialize(MarshallerContract marshaller, ServerAnnouncementChannel channel) async { - final permissions = await Future.wait(channel.permissions.map((element) async => marshaller.serializers.channelPermissionOverwrite.deserialize(element))); + Future> deserialize( + MarshallerContract marshaller, ServerAnnouncementChannel channel) async { + final permissions = await Future.wait(channel.permissions.map( + (element) async => marshaller.serializers.channelPermissionOverwrite + .deserialize(element))); return { 'id': channel.id.value, diff --git a/lib/infrastructure/internals/marshaller/factories/channels/server_category_channel_factory.dart b/lib/infrastructure/internals/marshaller/factories/channels/server_category_channel_factory.dart index 36c014b5..1d172d02 100644 --- a/lib/infrastructure/internals/marshaller/factories/channels/server_category_channel_factory.dart +++ b/lib/infrastructure/internals/marshaller/factories/channels/server_category_channel_factory.dart @@ -4,12 +4,14 @@ import 'package:mineral/api/server/channels/server_category_channel.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/channel_factory.dart'; -final class ServerCategoryChannelFactory implements ChannelFactoryContract { +final class ServerCategoryChannelFactory + implements ChannelFactoryContract { @override ChannelType get type => ChannelType.guildCategory; @override - Future> normalize(MarshallerContract marshaller, Map json) async { + Future> normalize( + MarshallerContract marshaller, Map json) async { final payload = { 'id': json['id'], 'type': json['type'], @@ -28,15 +30,18 @@ final class ServerCategoryChannelFactory implements ChannelFactoryContract serialize(MarshallerContract marshaller, Map json) async { + Future serialize( + MarshallerContract marshaller, Map json) async { final properties = await ChannelProperties.serializeCache(marshaller, json); return ServerCategoryChannel(properties); } @override - Future> deserialize(MarshallerContract marshaller, ServerCategoryChannel channel) async { - final permissions = await Future.wait(channel.permissions.map((element) async => - marshaller.serializers.channelPermissionOverwrite.deserialize(element))); + Future> deserialize( + MarshallerContract marshaller, ServerCategoryChannel channel) async { + final permissions = await Future.wait(channel.permissions.map( + (element) async => marshaller.serializers.channelPermissionOverwrite + .deserialize(element))); return { 'id': channel.id.value, diff --git a/lib/infrastructure/internals/marshaller/factories/channels/server_forum_channel_factory.dart b/lib/infrastructure/internals/marshaller/factories/channels/server_forum_channel_factory.dart index 29dbbc68..c02fc96a 100644 --- a/lib/infrastructure/internals/marshaller/factories/channels/server_forum_channel_factory.dart +++ b/lib/infrastructure/internals/marshaller/factories/channels/server_forum_channel_factory.dart @@ -8,12 +8,14 @@ import 'package:mineral/infrastructure/commons/utils.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/channel_factory.dart'; -final class ServerForumChannelFactory implements ChannelFactoryContract { +final class ServerForumChannelFactory + implements ChannelFactoryContract { @override ChannelType get type => ChannelType.guildForum; @override - Future> normalize(MarshallerContract marshaller, Map json) async { + Future> normalize( + MarshallerContract marshaller, Map json) async { final payload = { 'id': json['id'], 'type': json['type'], @@ -32,18 +34,28 @@ final class ServerForumChannelFactory implements ChannelFactoryContract serialize(MarshallerContract marshaller, Map json) async { + Future serialize( + MarshallerContract marshaller, Map json) async { final properties = await ChannelProperties.serializeCache(marshaller, json); return ServerForumChannel( properties, - sortOrder: Helper.createOrNull(field: json['default_sort_order'], fn: () => findInEnum(SortOrderType.values, json['default_sort_order'])), - layoutType: Helper.createOrNull(field: json['default_forum_layout'], fn: () => findInEnum(ForumLayoutType.values, json['default_forum_layout'])), + sortOrder: Helper.createOrNull( + field: json['default_sort_order'], + fn: () => + findInEnum(SortOrderType.values, json['default_sort_order'])), + layoutType: Helper.createOrNull( + field: json['default_forum_layout'], + fn: () => + findInEnum(ForumLayoutType.values, json['default_forum_layout'])), ); } @override - Future> deserialize(MarshallerContract marshaller, ServerForumChannel channel) async { - final permissions = await Future.wait(channel.permissions.map((element) async => marshaller.serializers.channelPermissionOverwrite.deserialize(element))); + Future> deserialize( + MarshallerContract marshaller, ServerForumChannel channel) async { + final permissions = await Future.wait(channel.permissions.map( + (element) async => marshaller.serializers.channelPermissionOverwrite + .deserialize(element))); return { 'id': channel.id.value, diff --git a/lib/infrastructure/internals/marshaller/factories/channels/server_stage_channel_factory.dart b/lib/infrastructure/internals/marshaller/factories/channels/server_stage_channel_factory.dart index 74346486..9e8ed9d5 100644 --- a/lib/infrastructure/internals/marshaller/factories/channels/server_stage_channel_factory.dart +++ b/lib/infrastructure/internals/marshaller/factories/channels/server_stage_channel_factory.dart @@ -4,12 +4,14 @@ import 'package:mineral/api/server/channels/server_stage_channel.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/channel_factory.dart'; -final class ServerStageChannelFactory implements ChannelFactoryContract { +final class ServerStageChannelFactory + implements ChannelFactoryContract { @override ChannelType get type => ChannelType.guildStageVoice; @override - Future> normalize(MarshallerContract marshaller, Map json) async { + Future> normalize( + MarshallerContract marshaller, Map json) async { final payload = { 'id': json['id'], 'type': json['type'], @@ -28,14 +30,18 @@ final class ServerStageChannelFactory implements ChannelFactoryContract serialize(MarshallerContract marshaller, Map json) async { + Future serialize( + MarshallerContract marshaller, Map json) async { final properties = await ChannelProperties.serializeCache(marshaller, json); return ServerStageChannel(properties); } @override - Future> deserialize(MarshallerContract marshaller, ServerStageChannel channel) async { - final permissions = await Future.wait(channel.permissions.map((element) async => marshaller.serializers.channelPermissionOverwrite.deserialize(element))); + Future> deserialize( + MarshallerContract marshaller, ServerStageChannel channel) async { + final permissions = await Future.wait(channel.permissions.map( + (element) async => marshaller.serializers.channelPermissionOverwrite + .deserialize(element))); return { 'id': channel.id.value, diff --git a/lib/infrastructure/internals/marshaller/factories/channels/server_text_channel_factory.dart b/lib/infrastructure/internals/marshaller/factories/channels/server_text_channel_factory.dart index 5c92464c..237a6a51 100644 --- a/lib/infrastructure/internals/marshaller/factories/channels/server_text_channel_factory.dart +++ b/lib/infrastructure/internals/marshaller/factories/channels/server_text_channel_factory.dart @@ -4,12 +4,14 @@ import 'package:mineral/api/server/channels/server_text_channel.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/channel_factory.dart'; -final class ServerTextChannelFactory implements ChannelFactoryContract { +final class ServerTextChannelFactory + implements ChannelFactoryContract { @override ChannelType get type => ChannelType.guildText; @override - Future> normalize(MarshallerContract marshaller, Map json) async { + Future> normalize( + MarshallerContract marshaller, Map json) async { final payload = { 'id': json['id'], 'type': json['type'], @@ -28,14 +30,18 @@ final class ServerTextChannelFactory implements ChannelFactoryContract serialize(MarshallerContract marshaller, Map json) async { + Future serialize( + MarshallerContract marshaller, Map json) async { final properties = await ChannelProperties.serializeCache(marshaller, json); return ServerTextChannel(properties); } @override - Future> deserialize(MarshallerContract marshaller, ServerTextChannel channel) async { - final permissions = await Future.wait(channel.permissions.map((element) async => marshaller.serializers.channelPermissionOverwrite.deserialize(element))); + Future> deserialize( + MarshallerContract marshaller, ServerTextChannel channel) async { + final permissions = await Future.wait(channel.permissions.map( + (element) async => marshaller.serializers.channelPermissionOverwrite + .deserialize(element))); return { 'id': channel.id.value, diff --git a/lib/infrastructure/internals/marshaller/factories/channels/server_voice_channel_factory.dart b/lib/infrastructure/internals/marshaller/factories/channels/server_voice_channel_factory.dart index 5488b48e..f80bce00 100644 --- a/lib/infrastructure/internals/marshaller/factories/channels/server_voice_channel_factory.dart +++ b/lib/infrastructure/internals/marshaller/factories/channels/server_voice_channel_factory.dart @@ -4,12 +4,14 @@ import 'package:mineral/api/server/channels/server_voice_channel.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/channel_factory.dart'; -final class ServerVoiceChannelFactory implements ChannelFactoryContract { +final class ServerVoiceChannelFactory + implements ChannelFactoryContract { @override ChannelType get type => ChannelType.guildVoice; @override - Future> normalize(MarshallerContract marshaller, Map json) async { + Future> normalize( + MarshallerContract marshaller, Map json) async { final payload = { 'id': json['id'], 'type': json['type'], @@ -27,15 +29,18 @@ final class ServerVoiceChannelFactory implements ChannelFactoryContract serialize(MarshallerContract marshaller, Map json) async { + Future serialize( + MarshallerContract marshaller, Map json) async { final properties = await ChannelProperties.serializeCache(marshaller, json); return ServerVoiceChannel(properties); } @override - Future> deserialize(MarshallerContract marshaller, ServerVoiceChannel channel) async { - final permissions = await Future.wait(channel.permissions.map((element) async => - marshaller.serializers.channelPermissionOverwrite.deserialize(element))); + Future> deserialize( + MarshallerContract marshaller, ServerVoiceChannel channel) async { + final permissions = await Future.wait(channel.permissions.map( + (element) async => marshaller.serializers.channelPermissionOverwrite + .deserialize(element))); return { 'id': channel.id.value, diff --git a/lib/infrastructure/internals/marshaller/factories/messages/private_message_factory.dart b/lib/infrastructure/internals/marshaller/factories/messages/private_message_factory.dart index 8ce06be8..85b76650 100644 --- a/lib/infrastructure/internals/marshaller/factories/messages/private_message_factory.dart +++ b/lib/infrastructure/internals/marshaller/factories/messages/private_message_factory.dart @@ -10,11 +10,13 @@ final class PrivateMessageFactory implements MessageFactory { Future serialize( MarshallerContract marshaller, Map json) async { final channel = json['channel'] as Channel; - final messageProperties = MessageProperties.fromJson(channel as PrivateChannel, json); + final messageProperties = + MessageProperties.fromJson(channel as PrivateChannel, json); final user = await marshaller.serializers.user.serialize(json['author']); - return PrivateMessage(messageProperties, userId: json['author']['id'], author: user); + return PrivateMessage(messageProperties, + userId: json['author']['id'], author: user); } @override @@ -23,7 +25,8 @@ final class PrivateMessageFactory implements MessageFactory { return { 'id': message.id, 'content': message.content, - 'embeds': message.embeds.map(marshaller.serializers.embed.deserialize).toList(), + 'embeds': + message.embeds.map(marshaller.serializers.embed.deserialize).toList(), 'channel_id': message.channel.id, 'created_at': message.createdAt.toIso8601String(), 'updated_at': message.updatedAt?.toIso8601String(), diff --git a/lib/infrastructure/internals/marshaller/factories/messages/server_message_factory.dart b/lib/infrastructure/internals/marshaller/factories/messages/server_message_factory.dart index 0dd14dcf..f98c4578 100644 --- a/lib/infrastructure/internals/marshaller/factories/messages/server_message_factory.dart +++ b/lib/infrastructure/internals/marshaller/factories/messages/server_message_factory.dart @@ -10,10 +10,12 @@ final class ServerMessageFactory implements MessageFactory { Future serialize( MarshallerContract marshaller, Map json) async { final channel = json['channel'] as Channel; - final server = await marshaller.dataStore.server.getServer(json['guild_id']); + final server = + await marshaller.dataStore.server.getServer(json['guild_id']); final member = server.members.list[json['author']['id']]; - final messageProperties = MessageProperties.fromJson(channel as ServerChannel, json); + final messageProperties = + MessageProperties.fromJson(channel as ServerChannel, json); return ServerMessage(messageProperties, author: member!); } @@ -24,7 +26,8 @@ final class ServerMessageFactory implements MessageFactory { return { 'id': message.id, 'content': message.content, - 'embeds': message.embeds.map(marshaller.serializers.embed.deserialize).toList(), + 'embeds': + message.embeds.map(marshaller.serializers.embed.deserialize).toList(), 'channel_id': message.channel.id, 'guild_id': message.channel.serverId, 'created_at': message.createdAt.toIso8601String(), diff --git a/lib/infrastructure/internals/marshaller/serializer_bucket.dart b/lib/infrastructure/internals/marshaller/serializer_bucket.dart index b096cdb2..899bfcfc 100644 --- a/lib/infrastructure/internals/marshaller/serializer_bucket.dart +++ b/lib/infrastructure/internals/marshaller/serializer_bucket.dart @@ -62,7 +62,8 @@ final class SerializerBucket { final SerializerContract sticker; - final SerializerContract channelPermissionOverwrite; + final SerializerContract + channelPermissionOverwrite; final SerializerContract serverMessage; @@ -87,7 +88,8 @@ final class SerializerBucket { serversAsset = ServerAssetsSerializer(marshaller), emojis = EmojiSerializer(marshaller), sticker = StickerSerializer(marshaller), - channelPermissionOverwrite = ChannelPermissionOverwriteSerializer(marshaller), + channelPermissionOverwrite = + ChannelPermissionOverwriteSerializer(marshaller), serverMessage = ServerMessageSerializer(marshaller), privateMessage = PrivateMessageSerializer(marshaller), embed = EmbedSerializer(marshaller), diff --git a/lib/infrastructure/internals/marshaller/serializers/channel_permission_overwrite_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/channel_permission_overwrite_serializer.dart index fcaf3799..d80fcce5 100644 --- a/lib/infrastructure/internals/marshaller/serializers/channel_permission_overwrite_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/channel_permission_overwrite_serializer.dart @@ -19,8 +19,9 @@ final class ChannelPermissionOverwriteSerializer 'deny': json['deny'], }; - final cacheKey = marshaller.cacheKey - .channelPermission(Snowflake(payload['id']), serverId: json['server_id']); + final cacheKey = marshaller.cacheKey.channelPermission( + Snowflake(payload['id']), + serverId: json['server_id']); await marshaller.cache.put(cacheKey, payload); return payload; diff --git a/lib/infrastructure/internals/marshaller/serializers/channel_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/channel_serializer.dart index e3ee1cab..226aa0ac 100644 --- a/lib/infrastructure/internals/marshaller/serializers/channel_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/channel_serializer.dart @@ -13,7 +13,8 @@ import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/channel_factory.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/serializer.dart'; -final class ChannelSerializer implements SerializerContract { +final class ChannelSerializer + implements SerializerContract { final MarshallerContract _marshaller; final List _factories = [ @@ -30,7 +31,8 @@ final class ChannelSerializer implements SerializerContract< @override Future> normalize(Map json) async { - final channelFactory = _factories.firstWhereOrNull((element) => element.type.value == json['type']); + final channelFactory = _factories + .firstWhereOrNull((element) => element.type.value == json['type']); if (channelFactory == null) { _marshaller.logger.warn('Channel type not found ${json['type']}'); return {}; @@ -41,7 +43,8 @@ final class ChannelSerializer implements SerializerContract< @override Future serialize(Map json) { - final channelFactory = _factories.firstWhereOrNull((element) => element.type.value == json['type']); + final channelFactory = _factories + .firstWhereOrNull((element) => element.type.value == json['type']); if (channelFactory == null) { _marshaller.logger.warn('Channel type not found ${json['type']}'); @@ -53,7 +56,8 @@ final class ChannelSerializer implements SerializerContract< @override Future> deserialize(Channel? channel) async { - final channelFactory = _factories.firstWhereOrNull((element) => element.type == channel?.type); + final channelFactory = + _factories.firstWhereOrNull((element) => element.type == channel?.type); if (channelFactory != null) { return channelFactory.deserialize(_marshaller, channel!); } diff --git a/lib/infrastructure/internals/marshaller/serializers/embed_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/embed_serializer.dart index 6a6c2e37..48ffb9ae 100644 --- a/lib/infrastructure/internals/marshaller/serializers/embed_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/embed_serializer.dart @@ -42,17 +42,23 @@ final class EmbedSerializer implements SerializerContract { title: json['title'], description: json['description'], type: Helper.createOrNull( - field: json['type'], fn: () => findInEnum(MessageEmbedType.values, json['type'])), + field: json['type'], + fn: () => findInEnum(MessageEmbedType.values, json['type'])), url: json['url'], timestamp: Helper.createOrNull( - field: json['timestamp'], fn: () => DateTime.tryParse(json['timestamp'])), + field: json['timestamp'], + fn: () => DateTime.tryParse(json['timestamp'])), assets: Helper.createOrNull( - field: json['assets'], fn: () => MessageEmbedAssets.fromJson(json['assets'])), + field: json['assets'], + fn: () => MessageEmbedAssets.fromJson(json['assets'])), provider: Helper.createOrNull( - field: json['provider'], fn: () => MessageEmbedProvider.fromJson(json['provider'])), + field: json['provider'], + fn: () => MessageEmbedProvider.fromJson(json['provider'])), fields: Helper.createOrNull( - field: json['fields'], fn: () => json['fields'].map(MessageEmbedField.fromJson).toList()), - color: Helper.createOrNull(field: json['color'], fn: () => Color.of(json['color'])), + field: json['fields'], + fn: () => json['fields'].map(MessageEmbedField.fromJson).toList()), + color: Helper.createOrNull( + field: json['color'], fn: () => Color.of(json['color'])), ); } diff --git a/lib/infrastructure/internals/marshaller/serializers/emoji_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/emoji_serializer.dart index 567a30ce..88199c3d 100644 --- a/lib/infrastructure/internals/marshaller/serializers/emoji_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/emoji_serializer.dart @@ -18,11 +18,13 @@ final class EmojiSerializer implements SerializerContract { 'available': json['available'] ?? false, 'animated': json['animated'] ?? false, 'roles': List.from(json['roles']) - .map((element) => _marshaller.cacheKey.serverEmoji(json['server_id'], element['id'])) + .map((element) => _marshaller.cacheKey + .serverEmoji(json['server_id'], element['id'])) .toList(), }; - final cacheKey = _marshaller.cacheKey.serverEmoji(json['server_id'], json['id']); + final cacheKey = + _marshaller.cacheKey.serverEmoji(json['server_id'], json['id']); await _marshaller.cache.put(cacheKey, payload); return payload; @@ -38,7 +40,8 @@ final class EmojiSerializer implements SerializerContract { return Emoji( id: json['id'], name: json['name'], - roles: roles.fold({}, (value, element) => {...value, element.id: element}), + roles: + roles.fold({}, (value, element) => {...value, element.id: element}), managed: json['managed'], animated: json['animated'], available: json['available'], diff --git a/lib/infrastructure/internals/marshaller/serializers/member_assets_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/member_assets_serializer.dart index 8adce777..0c29b789 100644 --- a/lib/infrastructure/internals/marshaller/serializers/member_assets_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/member_assets_serializer.dart @@ -20,7 +20,8 @@ final class MemberAssetsSerializer implements SerializerContract { 'banner': json['banner'], }; - final cacheKey = _marshaller.cacheKey.memberAssets(json['server_id'], json['user']['id']); + final cacheKey = _marshaller.cacheKey + .memberAssets(json['server_id'], json['user']['id']); await _marshaller.cache.put(cacheKey, payload); return payload; @@ -34,8 +35,8 @@ final class MemberAssetsSerializer implements SerializerContract { fn: () => ImageAsset(['avatars', json['member_id']], json['avatar'])), avatarDecoration: Helper.createOrNull( field: json['avatar_decoration'], - fn: () => - ImageAsset(['avatar-decorations', json['member_id']], json['avatar_decoration'])), + fn: () => ImageAsset(['avatar-decorations', json['member_id']], + json['avatar_decoration'])), banner: Helper.createOrNull( field: json['banner'], fn: () => ImageAsset(['banners', json['member_id']], json['banner'])), diff --git a/lib/infrastructure/internals/marshaller/serializers/member_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/member_serializer.dart index 0e647241..3351a458 100644 --- a/lib/infrastructure/internals/marshaller/serializers/member_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/member_serializer.dart @@ -28,10 +28,12 @@ final class MemberSerializer implements SerializerContract { 'nickname': json['nick'], 'global_name': json['user']['global_name'], 'discriminator': json['user']['discriminator'], - 'assets': _marshaller.cacheKey.memberAssets(json['server_id'], json['user']['id']), + 'assets': _marshaller.cacheKey + .memberAssets(json['server_id'], json['user']['id']), 'flags': json['flags'], 'roles': List.from(json['roles']) - .map((element) => _marshaller.cacheKey.serverRole(json['server_id'], element)) + .map((element) => + _marshaller.cacheKey.serverRole(json['server_id'], element)) .toList(), 'premium_since': json['premium_since'], 'public_flags': json['user']['public_flags'], @@ -48,7 +50,8 @@ final class MemberSerializer implements SerializerContract { 'server_id': json['server_id'], }; - final cacheKey = _marshaller.cacheKey.member(json['server_id'], json['user']['id']); + final cacheKey = + _marshaller.cacheKey.member(json['server_id'], json['user']['id']); await _marshaller.cache.put(cacheKey, payload); return payload; @@ -57,7 +60,8 @@ final class MemberSerializer implements SerializerContract { @override Future serialize(Map json) async { final rawAssets = await _marshaller.cache.getOrFail(json['assets']); - final assets = await _marshaller.serializers.memberAssets.serialize(rawAssets); + final assets = + await _marshaller.serializers.memberAssets.serialize(rawAssets); final rawRoles = await _marshaller.cache.getMany(json['roles']); final roles = await rawRoles.nonNulls.map((element) async { @@ -71,9 +75,11 @@ final class MemberSerializer implements SerializerContract { globalName: json['global_name'], discriminator: json['discriminator'], assets: assets, - flags: MemberFlagsManager(bitfieldToList(MemberFlag.values, json['flags'])), + flags: + MemberFlagsManager(bitfieldToList(MemberFlag.values, json['flags'])), premiumSince: Helper.createOrNull( - field: json['premium_since'], fn: () => DateTime.parse(json['premium_since'])), + field: json['premium_since'], + fn: () => DateTime.parse(json['premium_since'])), publicFlags: json['public_flags'], roles: MemberRoleManager.fromList(roles), isBot: json['is_bot'] ?? false, @@ -84,10 +90,12 @@ final class MemberSerializer implements SerializerContract { fn: () => DateTime.parse(json['communication_disabled_until']))), mfaEnabled: json['mfa_enabled'] ?? false, locale: json['locale'], - premiumType: PremiumTier.values - .firstWhere((e) => e == json['premium_type'], orElse: () => PremiumTier.none), + premiumType: PremiumTier.values.firstWhere( + (e) => e == json['premium_type'], + orElse: () => PremiumTier.none), joinedAt: Helper.createOrNull( - field: json['joined_at'], fn: () => DateTime.parse(json['joined_at'])), + field: json['joined_at'], + fn: () => DateTime.parse(json['joined_at'])), permissions: switch (json['permissions']) { int() => Permissions.fromInt(json['permissions']), String() => Permissions.fromInt(int.parse(json['permissions'])), @@ -106,10 +114,14 @@ final class MemberSerializer implements SerializerContract { @override Future> deserialize(Member member) async { - final rawAsset = await _marshaller.serializers.memberAssets.deserialize(member.assets); + final rawAsset = + await _marshaller.serializers.memberAssets.deserialize(member.assets); final rawRoles = await member.roles.list.entries.map((role) async { - final cacheKey = _marshaller.cacheKey.serverRole(member.server.id, role.key); - return {cacheKey: await _marshaller.serializers.role.deserialize(role.value)}; + final cacheKey = + _marshaller.cacheKey.serverRole(member.server.id, role.key); + return { + cacheKey: await _marshaller.serializers.role.deserialize(role.value) + }; }).wait; await _marshaller.cache.putMany({ diff --git a/lib/infrastructure/internals/marshaller/serializers/message_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/message_serializer.dart index e69de29b..8b137891 100644 --- a/lib/infrastructure/internals/marshaller/serializers/message_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/message_serializer.dart @@ -0,0 +1 @@ + diff --git a/lib/infrastructure/internals/marshaller/serializers/poll_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/poll_serializer.dart index 6c9424b8..d79f4d04 100644 --- a/lib/infrastructure/internals/marshaller/serializers/poll_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/poll_serializer.dart @@ -19,7 +19,8 @@ final class PollSerializer implements SerializerContract { final payload = { 'message_id': json['message_id'], 'question_text': json['question']['text'], - 'answers': List.from(json['answers']).map((element) => element['text']).toList(), + 'answers': + List.from(json['answers']).map((element) => element['text']).toList(), 'expiry': json['expiry'], 'allow_multiselect': json['allow_multiselect'], 'layout_type': json['layout_type'], @@ -40,11 +41,13 @@ final class PollSerializer implements SerializerContract { .map((element) => PollAnswer( content: element['text'], emoji: Helper.createOrNull( - field: element['emoji'], fn: () => PartialEmoji.fromUnicode(element['emoji'])))) + field: element['emoji'], + fn: () => PartialEmoji.fromUnicode(element['emoji'])))) .toList(), expireAt: Helper.createOrNull( field: json['expiry'], - fn: () => DateTime.parse(json['expiry']).difference(DateTime.now())), + fn: () => + DateTime.parse(json['expiry']).difference(DateTime.now())), isAllowMultiple: json['allow_multiselect'], layout: findInEnum(PollLayout.values, json['layout_type'])); } diff --git a/lib/infrastructure/internals/marshaller/serializers/private_message_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/private_message_serializer.dart index b8c46e77..6a04c8d2 100644 --- a/lib/infrastructure/internals/marshaller/serializers/private_message_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/private_message_serializer.dart @@ -6,7 +6,8 @@ import 'package:mineral/api/private/private_message.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/serializer.dart'; -final class PrivateMessageSerializer implements SerializerContract { +final class PrivateMessageSerializer + implements SerializerContract { final MarshallerContract marshaller; PrivateMessageSerializer(this.marshaller); @@ -23,7 +24,8 @@ final class PrivateMessageSerializer implements SerializerContract serialize(Map json) async { - final List embeds = await Future.wait(List.from(json['embeds']).map((message) async { + final List embeds = + await Future.wait(List.from(json['embeds']).map((message) async { return marshaller.serializers.embed.serialize(message); })); @@ -40,7 +43,9 @@ final class PrivateMessageSerializer implements SerializerContract { 'flags': json['flags'], }; - final cacheKey = marshaller.cacheKey.serverRole(json['server_id'], json['id']); + final cacheKey = + marshaller.cacheKey.serverRole(json['server_id'], json['id']); await marshaller.cache.put(cacheKey, payload); return payload; @@ -41,7 +42,7 @@ final class RoleSerializer implements SerializerContract { color: Color.of(payload['color'] ?? 0), hoist: payload['hoist'] ?? false, position: payload['position'] ?? 0, - permissions: switch(payload['permissions']) { + permissions: switch (payload['permissions']) { int() => Permissions.fromInt(payload['permissions']), String() => Permissions.fromInt(int.parse(payload['permissions'])), _ => Permissions.fromInt(0), diff --git a/lib/infrastructure/internals/marshaller/serializers/server_assets_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/server_assets_serializer.dart index ec9ce436..1b9260cf 100644 --- a/lib/infrastructure/internals/marshaller/serializers/server_assets_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/server_assets_serializer.dart @@ -17,15 +17,18 @@ final class ServerAssetsSerializer implements SerializerContract { final cacheKey = _marshaller.cacheKey.serverAssets(json['id']); await List.from(json['roles']).map((element) async { - return _marshaller.serializers.role.normalize({...element, 'server_id': json['id']}); + return _marshaller.serializers.role + .normalize({...element, 'server_id': json['id']}); }).wait; await List.from(json['emojis']).map((element) async { - return _marshaller.serializers.emojis.normalize({...element, 'server_id': json['id']}); + return _marshaller.serializers.emojis + .normalize({...element, 'server_id': json['id']}); }).wait; await List.from(json['stickers']).map((element) async { - return _marshaller.serializers.sticker.normalize({...element, 'server_id': json['id']}); + return _marshaller.serializers.sticker + .normalize({...element, 'server_id': json['id']}); }).wait; final payload = { @@ -35,13 +38,16 @@ final class ServerAssetsSerializer implements SerializerContract { 'discovery_splash': json['discovery_splash'], 'banner': json['banner'], 'stickers': List.from(json['stickers']) - .map((element) => _marshaller.cacheKey.sticker(json['id'], element['id'])) + .map((element) => + _marshaller.cacheKey.sticker(json['id'], element['id'])) .toList(), 'roles': List.from(json['roles']) - .map((element) => _marshaller.cacheKey.serverRole(json['id'], element['id'])) + .map((element) => + _marshaller.cacheKey.serverRole(json['id'], element['id'])) .toList(), 'emojis': List.from(json['emojis']) - .map((element) => _marshaller.cacheKey.serverEmoji(json['id'], element['id'])) + .map((element) => + _marshaller.cacheKey.serverEmoji(json['id'], element['id'])) .toList(), 'server_id': json['id'], }; @@ -72,24 +78,31 @@ final class ServerAssetsSerializer implements SerializerContract { emojis: EmojiManager.fromList(roles, emojis), stickers: StickerManager.fromList(stickers), icon: Helper.createOrNull( - field: json['icon'], fn: () => ImageAsset(['icons', json['server_id']], json['icon'])), + field: json['icon'], + fn: () => ImageAsset(['icons', json['server_id']], json['icon'])), splash: Helper.createOrNull( - field: json['splash'], fn: () => ImageAsset(['splashes', json['server_id']], json['splash'])), + field: json['splash'], + fn: () => + ImageAsset(['splashes', json['server_id']], json['splash'])), banner: Helper.createOrNull( - field: json['banner'], fn: () => ImageAsset(['banners', json['server_id']], json['banner'])), + field: json['banner'], + fn: () => ImageAsset(['banners', json['server_id']], json['banner'])), discoverySplash: Helper.createOrNull( field: json['discovery_splash'], - fn: () => ImageAsset(['discovery-splashes', json['id']], json['discovery_splash'])), + fn: () => ImageAsset( + ['discovery-splashes', json['id']], json['discovery_splash'])), serverId: Snowflake(json['server_id']), ); } @override Future> deserialize(ServerAsset object) async { - final emojis = await Future.wait(object.emojis.list.values - .map((element) async => _marshaller.serializers.emojis.deserialize(element))); - final stickers = await Future.wait(object.stickers.list.values - .map((element) async => _marshaller.serializers.sticker.deserialize(element))); + final emojis = await Future.wait(object.emojis.list.values.map( + (element) async => + _marshaller.serializers.emojis.deserialize(element))); + final stickers = await Future.wait(object.stickers.list.values.map( + (element) async => + _marshaller.serializers.sticker.deserialize(element))); return { 'emojis': emojis.map((element) => element['id']).toList(), diff --git a/lib/infrastructure/internals/marshaller/serializers/server_message_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/server_message_serializer.dart index 64ee9845..75e1d26d 100644 --- a/lib/infrastructure/internals/marshaller/serializers/server_message_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/server_message_serializer.dart @@ -5,7 +5,8 @@ import 'package:mineral/api/server/server_message.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/serializer.dart'; -final class ServerMessageSerializer implements SerializerContract { +final class ServerMessageSerializer + implements SerializerContract { final MarshallerContract marshaller; ServerMessageSerializer(this.marshaller); @@ -24,8 +25,8 @@ final class ServerMessageSerializer implements SerializerContract 'edited_timestamp': json['edited_timestamp'], }; - final cacheKey = - marshaller.cacheKey.message(Snowflake(json['channel_id']), Snowflake(json['id'])); + final cacheKey = marshaller.cacheKey + .message(Snowflake(json['channel_id']), Snowflake(json['id'])); await marshaller.cache.put(cacheKey, payload); return payload; @@ -33,13 +34,16 @@ final class ServerMessageSerializer implements SerializerContract @override Future serialize(Map json) async { - final channel = await marshaller.dataStore.channel.getChannel(Snowflake(json['channel_id'])); + final channel = await marshaller.dataStore.channel + .getChannel(Snowflake(json['channel_id'])); - final server = await marshaller.dataStore.server.getServer(json['server_id']); + final server = + await marshaller.dataStore.server.getServer(json['server_id']); final member = await marshaller.dataStore.member .getMember(serverId: server.id, memberId: json['author_id']); - final messageProperties = MessageProperties.fromJson(channel as ServerChannel, json); + final messageProperties = + MessageProperties.fromJson(channel as ServerChannel, json); return ServerMessage(messageProperties, author: member); } diff --git a/lib/infrastructure/internals/marshaller/serializers/server_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/server_serializer.dart index 86c2ed0a..d63eba1e 100644 --- a/lib/infrastructure/internals/marshaller/serializers/server_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/server_serializer.dart @@ -24,7 +24,8 @@ final class ServerSerializer implements SerializerContract { @override Future> normalize(Map json) async { await List.from(json['members']).map((element) async { - return _marshaller.serializers.member.normalize({...element, 'server_id': json['id']}); + return _marshaller.serializers.member + .normalize({...element, 'server_id': json['id']}); }).wait; await List.from(json['channels']).map((element) async { @@ -53,10 +54,12 @@ final class ServerSerializer implements SerializerContract { 'assets': _marshaller.cacheKey.serverAssets(json['id']), 'settings': _marshaller.cacheKey.serverSettings(json['id']), 'roles': List.from(json['roles']) - .map((element) => _marshaller.cacheKey.serverRole(json['id'], element['id'])) + .map((element) => + _marshaller.cacheKey.serverRole(json['id'], element['id'])) .toList(), 'members': List.from(json['members']) - .map((element) => _marshaller.cacheKey.member(json['id'], element['user']['id'])) + .map((element) => + _marshaller.cacheKey.member(json['id'], element['user']['id'])) .toList(), 'channels': List.from(json['channels']) .map((element) => _marshaller.cacheKey.channel(element['id'])) @@ -76,7 +79,8 @@ final class ServerSerializer implements SerializerContract { Future serialize(Map payload) async { final rawMembers = await _marshaller.cache.getMany(payload['members']); final members = await rawMembers.nonNulls.map((element) async { - return _marshaller.serializers.member.serialize({...element, 'server_id': payload['id']}); + return _marshaller.serializers.member + .serialize({...element, 'server_id': payload['id']}); }).wait; final rawRoles = await _marshaller.cache.getMany(payload['roles']); @@ -86,7 +90,8 @@ final class ServerSerializer implements SerializerContract { final rawChannels = await _marshaller.cache.getMany(payload['channels']); final channels = await rawChannels.nonNulls.map((element) async { - return _marshaller.serializers.channels.serialize(element) as Future; + return _marshaller.serializers.channels.serialize(element) + as Future; }).wait; final rawThreads = await _marshaller.cache.getMany(payload['threads']); @@ -103,10 +108,12 @@ final class ServerSerializer implements SerializerContract { final owner = await _marshaller.serializers.member.serialize(rawOwner); final rawAssets = await _marshaller.cache.getOrFail(payload['assets']); - final serverAssets = await _marshaller.serializers.serversAsset.serialize(rawAssets); + final serverAssets = + await _marshaller.serializers.serversAsset.serialize(rawAssets); final rawSettings = await _marshaller.cache.getOrFail(payload['settings']); - final serverSettings = await _marshaller.serializers.serverSettings.serialize(rawSettings); + final serverSettings = + await _marshaller.serializers.serverSettings.serialize(rawSettings); final server = Server( id: payload['id'], @@ -128,8 +135,10 @@ final class ServerSerializer implements SerializerContract { } for (final thread in server.threads.list.values) { - thread..server = server - ..parentChannel = server.channels.list[Snowflake(thread.channelId)] as ServerTextChannel; + thread + ..server = server + ..parentChannel = server.channels.list[Snowflake(thread.channelId)] + as ServerTextChannel; } for (final member in server.members.list.values) { @@ -154,16 +163,20 @@ final class ServerSerializer implements SerializerContract { 'roles': server.roles.list.keys .map((id) => _marshaller.cacheKey.serverRole(server.id, id)) .toList(), - 'members': - server.members.list.keys.map((id) => _marshaller.cacheKey.member(server.id, id)).toList(), - 'channels': server.channels.list.keys.map((id) => _marshaller.cacheKey.channel(id)).toList(), + 'members': server.members.list.keys + .map((id) => _marshaller.cacheKey.member(server.id, id)) + .toList(), + 'channels': server.channels.list.keys + .map((id) => _marshaller.cacheKey.channel(id)) + .toList(), 'threads': server.threads.list.keys .map((id) => _marshaller.cacheKey.thread(id)) .toList(), }; } - Future assignCategoryChannel(Snowflake serverId, ServerChannel channel) async { + Future assignCategoryChannel( + Snowflake serverId, ServerChannel channel) async { final categoryId = switch (channel) { ServerTextChannel(:final categoryId) => categoryId, ServerVoiceChannel(:final categoryId) => categoryId, @@ -179,8 +192,9 @@ final class ServerSerializer implements SerializerContract { final channelCacheKey = _marshaller.cacheKey.channel(categoryId); final rawChannel = await _marshaller.cache.get(channelCacheKey); - final category = - rawChannel != null ? await _marshaller.serializers.channels.serialize(rawChannel) : null; + final category = rawChannel != null + ? await _marshaller.serializers.channels.serialize(rawChannel) + : null; if (category is ServerCategoryChannel?) { switch (channel) { diff --git a/lib/infrastructure/internals/marshaller/serializers/server_settings_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/server_settings_serializer.dart index b9292d80..f2c6c74d 100644 --- a/lib/infrastructure/internals/marshaller/serializers/server_settings_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/server_settings_serializer.dart @@ -9,7 +9,8 @@ import 'package:mineral/infrastructure/commons/utils.dart'; import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; import 'package:mineral/infrastructure/internals/marshaller/types/serializer.dart'; -final class ServerSettingsSerializer implements SerializerContract { +final class ServerSettingsSerializer + implements SerializerContract { final MarshallerContract _marshaller; ServerSettingsSerializer(this._marshaller); @@ -43,7 +44,8 @@ final class ServerSettingsSerializer implements SerializerContract serialize(Map json) async { - final subscription = await _marshaller.serializers.serverSubscription.serialize({ + final subscription = + await _marshaller.serializers.serverSubscription.serialize({ 'premium_tier': json['premium_tier'], 'premium_subscription_count': json['premium_subscription_count'], 'premium_progress_bar_enabled': json['premium_progress_bar_enabled'], @@ -53,14 +55,17 @@ final class ServerSettingsSerializer implements SerializerContract.from(json['features']), mfaLevel: findInEnum(MfaLevel.values, json['mfa_level']), - systemChannelFlags: bitfieldToList(SystemChannelFlag.values, json['system_channel_flags']), + systemChannelFlags: bitfieldToList( + SystemChannelFlag.values, json['system_channel_flags']), vanityUrlCode: json['vanity_url_code'], subscription: subscription, preferredLocale: json['preferred_locale'], @@ -76,14 +81,16 @@ final class ServerSettingsSerializer implements SerializerContract { +final class ServerSubscriptionSerializer + implements SerializerContract { final MarshallerContract _marshaller; ServerSubscriptionSerializer(this._marshaller); diff --git a/lib/infrastructure/internals/marshaller/serializers/sticker_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/sticker_serializer.dart index 8ceec618..509b4a0d 100644 --- a/lib/infrastructure/internals/marshaller/serializers/sticker_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/sticker_serializer.dart @@ -26,7 +26,8 @@ final class StickerSerializer implements SerializerContract { 'server_id': json['server_id'], }; - final cacheKey = _marshaller.cacheKey.sticker(Snowflake(json['server_id']), json['id']); + final cacheKey = + _marshaller.cacheKey.sticker(Snowflake(json['server_id']), json['id']); await _marshaller.cache.put(cacheKey, payload); return payload; @@ -37,13 +38,15 @@ final class StickerSerializer implements SerializerContract { return Sticker( id: Snowflake(json['id']), name: json['name'], - type: StickerType.values.firstWhere((element) => element.value == json['type']), + type: StickerType.values + .firstWhere((element) => element.value == json['type']), isAvailable: json['available'], packId: json['pack_id'], description: json['description'], tags: json['tags'], asset: json['asset'], - formatType: FormatType.values.firstWhere((element) => element.value == json['format_type']), + formatType: FormatType.values + .firstWhere((element) => element.value == json['format_type']), sortValue: json['sort_value'], serverId: Snowflake(json['server_id']), ); diff --git a/lib/infrastructure/internals/marshaller/serializers/thread_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/thread_serializer.dart index 046b96a7..4fe944ff 100644 --- a/lib/infrastructure/internals/marshaller/serializers/thread_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/thread_serializer.dart @@ -13,9 +13,10 @@ final class ThreadSerializer implements SerializerContract { @override Future> normalize(Map json) async { - final membersIds = List.from(json['members'] ?? [json['owner_id'] as String]) - .map((id) => _marshaller.cacheKey.thread(id)) - .toList(); + final membersIds = + List.from(json['members'] ?? [json['owner_id'] as String]) + .map((id) => _marshaller.cacheKey.thread(id)) + .toList(); final payload = { 'id': json['id'], @@ -25,7 +26,8 @@ final class ThreadSerializer implements SerializerContract { 'channel_id': json['parent_id'], 'metadata': { 'archived': json['thread_metadata']['archived'], - 'auto_archive_duration': json['thread_metadata']['auto_archive_duration'], + 'auto_archive_duration': json['thread_metadata'] + ['auto_archive_duration'], 'locked': json['thread_metadata']['locked'], 'archive_timestamp': json['thread_metadata']['archive_timestamp'], 'invitable': json['thread_metadata']['invitable'], @@ -52,7 +54,11 @@ final class ThreadSerializer implements SerializerContract { final permissionOverwrites = await Helper.createOrNullAsync( field: json['permission_overwrites'], fn: () async => Future.wait( - List.from(json['permission_overwrites']).map((json) async => _marshaller.serializers.channelPermissionOverwrite.serialize(json)).toList(), + List.from(json['permission_overwrites']) + .map((json) async => _marshaller + .serializers.channelPermissionOverwrite + .serialize(json)) + .toList(), )); final thread = ThreadChannel( @@ -64,27 +70,34 @@ final class ThreadSerializer implements SerializerContract { archived: json['metadata']['archived'], autoArchiveDuration: json['metadata']['auto_archive_duration'], locked: json['metadata']['locked'], - archiveTimestamp: json['metadata']['archive_timestamp'] != null ? DateTime.parse(json['metadata']['archive_timestamp']) : null, + archiveTimestamp: json['metadata']['archive_timestamp'] != null + ? DateTime.parse(json['metadata']['archive_timestamp']) + : null, invitable: json['metadata']['invitable'], isPublic: json['metadata']['is_public'], ), lastMessageId: json['last_message_id'], rateLimitPerUser: json['rate_limit_per_user'], - lastPinTimestamp: Helper.createOrNull(field: json['last_pin_timestamp'], fn: () => DateTime.parse(json['last_pin_timestamp'])), + lastPinTimestamp: Helper.createOrNull( + field: json['last_pin_timestamp'], + fn: () => DateTime.parse(json['last_pin_timestamp'])), messageCount: json['message_count'], flags: json['flags'], ownerId: json['owner_id'], permissions: permissionOverwrites ?? [], ); - final owner = await _marshaller.dataStore.member.getMember(serverId: thread.serverId, memberId: Snowflake(thread.ownerId)); - final rawMembers = await _marshaller.cache.getMany(json['members_ids'] as List); + final owner = await _marshaller.dataStore.member.getMember( + serverId: thread.serverId, memberId: Snowflake(thread.ownerId)); + final rawMembers = + await _marshaller.cache.getMany(json['members_ids'] as List); final membersList = await rawMembers.nonNulls.map((element) async { return _marshaller.serializers.member.serialize(element); }).wait; - final members = membersList.fold({}, (Map cc, Member member) { + final members = membersList.fold({}, + (Map cc, Member member) { cc[member.id] = member; return cc; }); @@ -109,7 +122,8 @@ final class ThreadSerializer implements SerializerContract { 'archived': channel.metadata.archived, 'auto_archive_duration': channel.metadata.autoArchiveDuration, 'locked': channel.metadata.locked, - 'archive_timestamp': channel.metadata.archiveTimestamp?.toIso8601String(), + 'archive_timestamp': + channel.metadata.archiveTimestamp?.toIso8601String(), 'invitable': channel.metadata.invitable, 'is_public': channel.metadata.isPublic, }, @@ -119,7 +133,9 @@ final class ThreadSerializer implements SerializerContract { 'last_pin_timestamp': channel.lastPinTimestamp?.toIso8601String(), 'message_count': channel.messageCount, 'flags': channel.flags, - 'members_ids': channel.members.keys.map((id) => _marshaller.cacheKey.member(channel.serverId, id)).toList(), + 'members_ids': channel.members.keys + .map((id) => _marshaller.cacheKey.member(channel.serverId, id)) + .toList(), }; } } diff --git a/lib/infrastructure/internals/marshaller/serializers/user_assets_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/user_assets_serializer.dart index 4766627a..67ae940a 100644 --- a/lib/infrastructure/internals/marshaller/serializers/user_assets_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/user_assets_serializer.dart @@ -33,8 +33,8 @@ final class UserAssetsSerializer implements SerializerContract { fn: () => ImageAsset(['avatars', json['user_id']], json['avatar'])), avatarDecoration: Helper.createOrNull( field: json['avatar_decoration'], - fn: () => - ImageAsset(['avatar-decorations', json['user_id']], json['avatar_decoration'])), + fn: () => ImageAsset(['avatar-decorations', json['user_id']], + json['avatar_decoration'])), banner: Helper.createOrNull( field: json['banner'], fn: () => ImageAsset(['banners', json['user_id']], json['banner'])), diff --git a/lib/infrastructure/internals/marshaller/serializers/user_serializer.dart b/lib/infrastructure/internals/marshaller/serializers/user_serializer.dart index 740649cf..aec40dc3 100644 --- a/lib/infrastructure/internals/marshaller/serializers/user_serializer.dart +++ b/lib/infrastructure/internals/marshaller/serializers/user_serializer.dart @@ -42,7 +42,8 @@ final class UserSerializer implements SerializerContract { @override Future serialize(Map json) async { final rawAssets = await _marshaller.cache.getOrFail(json['assets']); - final assets = await _marshaller.serializers.userAssets.serialize(rawAssets); + final assets = + await _marshaller.serializers.userAssets.serialize(rawAssets); return User( id: json['id'], @@ -56,12 +57,14 @@ final class UserSerializer implements SerializerContract { verified: json['verified'], email: json['email'], flags: json['flags'], - premiumType: PremiumTier.values - .firstWhere((e) => e == json['premium_type'], orElse: () => PremiumTier.none), + premiumType: PremiumTier.values.firstWhere( + (e) => e == json['premium_type'], + orElse: () => PremiumTier.none), publicFlags: json['public_flags'], assets: assets, createdAt: Helper.createOrNull( - field: json['created_at'], fn: () => DateTime.parse(json['created_at'])), + field: json['created_at'], + fn: () => DateTime.parse(json['created_at'])), // TODO: Implement presence deserialization presence: null, ); diff --git a/lib/infrastructure/internals/marshaller/types/channel_factory.dart b/lib/infrastructure/internals/marshaller/types/channel_factory.dart index 166dd52e..713b7c07 100644 --- a/lib/infrastructure/internals/marshaller/types/channel_factory.dart +++ b/lib/infrastructure/internals/marshaller/types/channel_factory.dart @@ -6,7 +6,10 @@ import 'package:mineral/infrastructure/internals/marshaller/marshaller.dart'; abstract interface class ChannelFactoryContract { ChannelType get type; - FutureOr> normalize(MarshallerContract marshaller, Map json); - FutureOr serialize(MarshallerContract marshaller, Map json); - FutureOr> deserialize(MarshallerContract marshaller, T channel); + FutureOr> normalize( + MarshallerContract marshaller, Map json); + FutureOr serialize( + MarshallerContract marshaller, Map json); + FutureOr> deserialize( + MarshallerContract marshaller, T channel); } diff --git a/lib/infrastructure/internals/packets/listenable_packet.dart b/lib/infrastructure/internals/packets/listenable_packet.dart index e1d0031b..3ee4f5bf 100644 --- a/lib/infrastructure/internals/packets/listenable_packet.dart +++ b/lib/infrastructure/internals/packets/listenable_packet.dart @@ -5,7 +5,9 @@ import 'package:mineral/infrastructure/internals/packets/packet_type.dart'; import 'package:mineral/infrastructure/internals/wss/shard_message.dart'; typedef DispatchEvent = Function( - {required Event event, required List params, bool Function(String?)? constraint}); + {required Event event, + required List params, + bool Function(String?)? constraint}); abstract interface class ListenablePacket { PacketType get packetType; diff --git a/lib/infrastructure/internals/packets/listeners/channel_create_packet.dart b/lib/infrastructure/internals/packets/listeners/channel_create_packet.dart index 0535ba7f..2b8f8db6 100644 --- a/lib/infrastructure/internals/packets/listeners/channel_create_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/channel_create_packet.dart @@ -18,18 +18,22 @@ final class ChannelCreatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final rawChannel = await marshaller.serializers.channels.normalize(message.payload); + final rawChannel = + await marshaller.serializers.channels.normalize(message.payload); final channel = await marshaller.serializers.channels.serialize(rawChannel); return switch (channel) { ServerChannel() => registerServerChannel(channel, dispatch), PrivateChannel() => registerPrivateChannel(channel, dispatch), - _ => logger.warn("Unknown channel type: $channel contact Mineral's core team.") + _ => logger + .warn("Unknown channel type: $channel contact Mineral's core team.") }; } - Future registerServerChannel(ServerChannel channel, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(channel.serverId); + Future registerServerChannel( + ServerChannel channel, DispatchEvent dispatch) async { + final server = + await marshaller.dataStore.server.getServer(channel.serverId); final serverCacheKey = marshaller.cacheKey.server(server.id); channel.server = server; @@ -41,7 +45,8 @@ final class ChannelCreatePacket implements ListenablePacket { dispatch(event: Event.serverChannelCreate, params: [channel]); } - Future registerPrivateChannel(PrivateChannel channel, DispatchEvent dispatch) async { + Future registerPrivateChannel( + PrivateChannel channel, DispatchEvent dispatch) async { dispatch(event: Event.privateChannelCreate, params: [channel]); } } diff --git a/lib/infrastructure/internals/packets/listeners/channel_delete_packet.dart b/lib/infrastructure/internals/packets/listeners/channel_delete_packet.dart index 8cc0367b..9f62bc4c 100644 --- a/lib/infrastructure/internals/packets/listeners/channel_delete_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/channel_delete_packet.dart @@ -17,7 +17,8 @@ final class ChannelDeletePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final rawChannel = await marshaller.serializers.channels.normalize(message.payload); + final rawChannel = + await marshaller.serializers.channels.normalize(message.payload); final channel = await marshaller.serializers.channels.serialize(rawChannel); switch (channel) { @@ -26,8 +27,10 @@ final class ChannelDeletePacket implements ListenablePacket { } } - Future registerServerChannel(ServerChannel channel, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(channel.serverId); + Future registerServerChannel( + ServerChannel channel, DispatchEvent dispatch) async { + final server = + await marshaller.dataStore.server.getServer(channel.serverId); final serverCacheKey = marshaller.cacheKey.server(server.id); final channelCacheKey = marshaller.cacheKey.channel(channel.id); diff --git a/lib/infrastructure/internals/packets/listeners/channel_pins_update_packet.dart b/lib/infrastructure/internals/packets/listeners/channel_pins_update_packet.dart index a6b13d3c..899c7f31 100644 --- a/lib/infrastructure/internals/packets/listeners/channel_pins_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/channel_pins_update_packet.dart @@ -18,18 +18,22 @@ final class ChannelPinsUpdatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final rawChannel = await marshaller.serializers.channels.normalize(message.payload); + final rawChannel = + await marshaller.serializers.channels.normalize(message.payload); final channel = await marshaller.serializers.channels.serialize(rawChannel); return switch (channel) { ServerChannel() => registerServerChannelPins(channel, dispatch), PrivateChannel() => registerPrivateChannelPins(channel, dispatch), - _ => logger.warn("Unknown channel type: $channel contact Mineral's core team.") + _ => logger + .warn("Unknown channel type: $channel contact Mineral's core team.") }; } - Future registerServerChannelPins(ServerChannel channel, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(channel.serverId); + Future registerServerChannelPins( + ServerChannel channel, DispatchEvent dispatch) async { + final server = + await marshaller.dataStore.server.getServer(channel.serverId); server.channels.list.update(channel.id, (_) => channel); @@ -41,7 +45,8 @@ final class ChannelPinsUpdatePacket implements ListenablePacket { dispatch(event: Event.serverChannelPinsUpdate, params: [server, channel]); } - Future registerPrivateChannelPins(PrivateChannel channel, DispatchEvent dispatch) async { + Future registerPrivateChannelPins( + PrivateChannel channel, DispatchEvent dispatch) async { dispatch(event: Event.privateChannelPinsUpdate, params: [channel]); } } diff --git a/lib/infrastructure/internals/packets/listeners/channel_update_packet.dart b/lib/infrastructure/internals/packets/listeners/channel_update_packet.dart index 88e80e66..e5bf1fcf 100644 --- a/lib/infrastructure/internals/packets/listeners/channel_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/channel_update_packet.dart @@ -23,18 +23,24 @@ final class ChannelUpdatePacket implements ListenablePacket { ? await marshaller.serializers.channels.serialize(rawBeforeChannel) : null; - final rawChannel = await marshaller.serializers.channels.normalize(message.payload); + final rawChannel = + await marshaller.serializers.channels.normalize(message.payload); final channel = await marshaller.serializers.channels.serialize(rawChannel); return switch (channel) { - ServerChannel() => registerServerChannel(channel, beforeChannel as ServerChannel?, dispatch), - PrivateChannel() => registerPrivateChannel(channel, beforeChannel as PrivateChannel?, dispatch), - _ => logger.warn("Unknown channel type: $channel contact Mineral's core team.") + ServerChannel() => registerServerChannel( + channel, beforeChannel as ServerChannel?, dispatch), + PrivateChannel() => registerPrivateChannel( + channel, beforeChannel as PrivateChannel?, dispatch), + _ => logger + .warn("Unknown channel type: $channel contact Mineral's core team.") }; } - Future registerServerChannel(ServerChannel channel, ServerChannel? before, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(channel.serverId); + Future registerServerChannel(ServerChannel channel, + ServerChannel? before, DispatchEvent dispatch) async { + final server = + await marshaller.dataStore.server.getServer(channel.serverId); channel.server = server; server.channels.list.update(channel.id, (_) => channel); @@ -47,7 +53,8 @@ final class ChannelUpdatePacket implements ListenablePacket { dispatch(event: Event.serverChannelUpdate, params: [before, channel]); } - Future registerPrivateChannel(PrivateChannel channel, PrivateChannel? before, DispatchEvent dispatch) async { + Future registerPrivateChannel(PrivateChannel channel, + PrivateChannel? before, DispatchEvent dispatch) async { dispatch(event: Event.serverChannelUpdate, params: [before, channel]); } } diff --git a/lib/infrastructure/internals/packets/listeners/guild_ban_add_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_ban_add_packet.dart index 52237e7f..54d03872 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_ban_add_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_ban_add_packet.dart @@ -16,8 +16,10 @@ final class GuildBanAddPacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); - final user = await marshaller.serializers.user.serialize(message.payload['user']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); + final user = + await marshaller.serializers.user.serialize(message.payload['user']); final member = server.members.list[user.id]; final memberId = message.payload['user']['id']; diff --git a/lib/infrastructure/internals/packets/listeners/guild_ban_remove_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_ban_remove_packet.dart index 32b91228..9f3edd48 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_ban_remove_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_ban_remove_packet.dart @@ -16,8 +16,10 @@ final class GuildBanRemovePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); - final user = await marshaller.serializers.user.serialize(message.payload['user']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); + final user = + await marshaller.serializers.user.serialize(message.payload['user']); dispatch(event: Event.serverBanRemove, params: [user, server]); } diff --git a/lib/infrastructure/internals/packets/listeners/guild_create_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_create_packet.dart index 27af1fb7..035b98d6 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_create_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_create_packet.dart @@ -19,7 +19,8 @@ final class GuildCreatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final rawServer = await marshaller.serializers.server.normalize(message.payload); + final rawServer = + await marshaller.serializers.server.normalize(message.payload); final server = await marshaller.serializers.server.serialize(rawServer); final bot = ioc.resolve(); diff --git a/lib/infrastructure/internals/packets/listeners/guild_emojis_update_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_emojis_update_packet.dart index 0d4d97d1..3c5f06bb 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_emojis_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_emojis_update_packet.dart @@ -17,11 +17,13 @@ final class GuildEmojisUpdatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); final serverCacheKey = marshaller.cacheKey.server(server.id); final rawEmojis = await List.from(message.payload['emojis']) - .map((element) async => marshaller.serializers.emojis.normalize(element)) + .map( + (element) async => marshaller.serializers.emojis.normalize(element)) .wait; final emojis = await rawEmojis.map((element) async { diff --git a/lib/infrastructure/internals/packets/listeners/guild_member_add_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_member_add_packet.dart index 3346160e..f967884b 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_member_add_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_member_add_packet.dart @@ -16,9 +16,11 @@ final class GuildMemberAddPacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); - final rawMember = await marshaller.serializers.member.normalize(message.payload); + final rawMember = + await marshaller.serializers.member.normalize(message.payload); final member = await marshaller.serializers.member.serialize(rawMember); server.members.list.putIfAbsent(member.id, () => member); diff --git a/lib/infrastructure/internals/packets/listeners/guild_member_chunk_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_member_chunk_packet.dart index 5dae6e60..77479eeb 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_member_chunk_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_member_chunk_packet.dart @@ -16,15 +16,18 @@ final class GuildMemberChunkPacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); - final rawMembers = await List.from(message.payload['members']).map((element) async { + final rawMembers = + await List.from(message.payload['members']).map((element) async { return marshaller.serializers.member.normalize(element); }).wait; await rawMembers.nonNulls.map((element) async { final member = await marshaller.serializers.member.serialize(element); - server.members.list.update(member.id, (value) => member, ifAbsent: () => member); + server.members.list + .update(member.id, (value) => member, ifAbsent: () => member); }).wait; final presences = message.payload['presences']; diff --git a/lib/infrastructure/internals/packets/listeners/guild_member_remove_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_member_remove_packet.dart index 2f90b1b5..e4c3bf6b 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_member_remove_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_member_remove_packet.dart @@ -16,7 +16,8 @@ final class GuildMemberRemovePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); final memberId = message.payload['user']['id']; final serverCacheKey = marshaller.cacheKey.server(server.id); diff --git a/lib/infrastructure/internals/packets/listeners/guild_member_update_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_member_update_packet.dart index e8e1453d..1d0d8545 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_member_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_member_update_packet.dart @@ -16,14 +16,16 @@ final class GuildMemberUpdatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); final before = marshaller.dataStore.member.getMember( serverId: server.id, memberId: message.payload['user']['id'], ); - final rawMember = await marshaller.serializers.member.normalize(message.payload); + final rawMember = + await marshaller.serializers.member.normalize(message.payload); final member = await marshaller.serializers.member.serialize(rawMember); member.server = server; diff --git a/lib/infrastructure/internals/packets/listeners/guild_role_create_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_role_create_packet.dart index 2142d863..f574e452 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_role_create_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_role_create_packet.dart @@ -16,7 +16,8 @@ final class GuildRoleCreatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); final rawRole = await marshaller.serializers.role.normalize({ ...message.payload['role'], 'server_id': server.id, diff --git a/lib/infrastructure/internals/packets/listeners/guild_role_delete_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_role_delete_packet.dart index eb959826..e007b194 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_role_delete_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_role_delete_packet.dart @@ -16,13 +16,16 @@ final class GuildRoleDeletePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); final roleId = message.payload['role']['id']; final roleCacheKey = marshaller.cacheKey.serverRole(server.id, roleId); final rawRole = await marshaller.cache.get(roleCacheKey); - final role = rawRole != null ? await marshaller.serializers.role.serialize(rawRole) : null; + final role = rawRole != null + ? await marshaller.serializers.role.serialize(rawRole) + : null; server.roles.list.remove(roleId); diff --git a/lib/infrastructure/internals/packets/listeners/guild_role_update_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_role_update_packet.dart index 471598df..81aaa57d 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_role_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_role_update_packet.dart @@ -16,14 +16,20 @@ final class GuildRoleUpdatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final serverCacheKey = marshaller.cacheKey.server(message.payload['guild_id']); - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); + final serverCacheKey = + marshaller.cacheKey.server(message.payload['guild_id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); - final roleCacheKey = marshaller.cacheKey.serverRole(server.id, message.payload['role']['id']); + final roleCacheKey = marshaller.cacheKey + .serverRole(server.id, message.payload['role']['id']); final rawBefore = await marshaller.cache.get(roleCacheKey); - final before = rawBefore != null ? marshaller.serializers.role.serialize(rawBefore) : null; + final before = rawBefore != null + ? marshaller.serializers.role.serialize(rawBefore) + : null; - final rawRole = await marshaller.serializers.role.normalize(message.payload['role']); + final rawRole = + await marshaller.serializers.role.normalize(message.payload['role']); final role = await marshaller.serializers.role.serialize(rawRole); server.roles.list.update(role.id, (_) => role); diff --git a/lib/infrastructure/internals/packets/listeners/guild_stickers_update_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_stickers_update_packet.dart index bdac7ffe..236e6e53 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_stickers_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_stickers_update_packet.dart @@ -17,9 +17,11 @@ final class GuildStickersUpdatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); - final rawStickers = await List.from(message.payload['stickers']).map((element) async { + final rawStickers = + await List.from(message.payload['stickers']).map((element) async { return marshaller.serializers.sticker.normalize({ 'server_id': server.id, ...element, @@ -34,6 +36,7 @@ final class GuildStickersUpdatePacket implements ListenablePacket { server.assets.stickers = stickerManager; - dispatch(event: Event.serverStickersUpdate, params: [stickerManager, server]); + dispatch( + event: Event.serverStickersUpdate, params: [stickerManager, server]); } } diff --git a/lib/infrastructure/internals/packets/listeners/guild_update_packet.dart b/lib/infrastructure/internals/packets/listeners/guild_update_packet.dart index 94c19bc9..a2e7326e 100644 --- a/lib/infrastructure/internals/packets/listeners/guild_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/guild_update_packet.dart @@ -18,10 +18,12 @@ final class GuildUpdatePacket implements ListenablePacket { Future listen(ShardMessage message, DispatchEvent dispatch) async { final serverCacheKey = marshaller.cacheKey.server(message.payload['id']); final rawServer = await marshaller.cache.get(serverCacheKey); - final before = - rawServer != null ? await marshaller.serializers.server.serialize(rawServer) : null; + final before = rawServer != null + ? await marshaller.serializers.server.serialize(rawServer) + : null; - final rawAfter = await marshaller.serializers.server.normalize(message.payload); + final rawAfter = + await marshaller.serializers.server.normalize(message.payload); final after = await marshaller.serializers.server.serialize(rawAfter); dispatch(event: Event.serverUpdate, params: [before, after]); diff --git a/lib/infrastructure/internals/packets/listeners/interactions/button_interaction_create_packet.dart b/lib/infrastructure/internals/packets/listeners/interactions/button_interaction_create_packet.dart index e3e44a8a..88799f89 100644 --- a/lib/infrastructure/internals/packets/listeners/interactions/button_interaction_create_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/interactions/button_interaction_create_packet.dart @@ -23,16 +23,19 @@ final class ButtonInteractionCreatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final type = InteractionType.values.firstWhereOrNull((e) => e.value == message.payload['type']); + final type = InteractionType.values + .firstWhereOrNull((e) => e.value == message.payload['type']); - final componentType = ComponentType.values - .firstWhereOrNull((e) => e.value == message.payload['data']['component_type']); + final componentType = ComponentType.values.firstWhereOrNull( + (e) => e.value == message.payload['data']['component_type']); - if (type == InteractionType.messageComponent && componentType == ComponentType.button) { + if (type == InteractionType.messageComponent && + componentType == ComponentType.button) { final String? serverId = message.payload['guild']?['id']; final metadata = message.payload['message']['interaction_metadata']; - final type = ComponentType.values.firstWhereOrNull((e) => e.value == metadata['type']); + final type = ComponentType.values + .firstWhereOrNull((e) => e.value == metadata['type']); if (type == null) { logger.warn('Component type ${metadata['type']} not found'); @@ -46,13 +49,15 @@ final class ButtonInteractionCreatePacket implements ListenablePacket { } } - Future _handleServerButton(Map payload, DispatchEvent dispatch) async { + Future _handleServerButton( + Map payload, DispatchEvent dispatch) async { final message = await marshaller.dataStore.message.getServerMessage( messageId: Snowflake(payload['message']['id']), channelId: Snowflake(payload['channel_id'])); final metadata = payload['message']['interaction_metadata']; - final type = ButtonType.values.firstWhereOrNull((e) => e.value == metadata['type']); + final type = + ButtonType.values.firstWhereOrNull((e) => e.value == metadata['type']); if (type == null) { logger.warn('Button type ${metadata['type']} not found'); @@ -75,13 +80,15 @@ final class ButtonInteractionCreatePacket implements ListenablePacket { constraint: (String? customId) => customId == ctx.customId); } - Future _handlePrivateButton(Map payload, DispatchEvent dispatch) async { + Future _handlePrivateButton( + Map payload, DispatchEvent dispatch) async { final message = await marshaller.dataStore.message.getPrivateMessage( messageId: Snowflake(payload['message']['id']), channelId: Snowflake(payload['channel_id'])); final metadata = payload['message']['interaction_metadata']; - final type = ButtonType.values.firstWhereOrNull((e) => e.value == metadata['type']); + final type = + ButtonType.values.firstWhereOrNull((e) => e.value == metadata['type']); if (type == null) { logger.warn('Button type ${metadata['type']} not found'); diff --git a/lib/infrastructure/internals/packets/listeners/interactions/command_interaction_create_packet.dart b/lib/infrastructure/internals/packets/listeners/interactions/command_interaction_create_packet.dart index 24e5716a..f94b5da2 100644 --- a/lib/infrastructure/internals/packets/listeners/interactions/command_interaction_create_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/interactions/command_interaction_create_packet.dart @@ -20,7 +20,8 @@ final class CommandInteractionCreatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { final interactionManager = ioc.resolve(); - final type = InteractionType.values.firstWhereOrNull((e) => e.value == message.payload['type']); + final type = InteractionType.values + .firstWhereOrNull((e) => e.value == message.payload['type']); if (type == InteractionType.applicationCommand) { await interactionManager.dispatcher.dispatch(message.payload); diff --git a/lib/infrastructure/internals/packets/listeners/interactions/dialog_interaction_create_packet.dart b/lib/infrastructure/internals/packets/listeners/interactions/dialog_interaction_create_packet.dart index e7d2f5ca..2906d5f5 100644 --- a/lib/infrastructure/internals/packets/listeners/interactions/dialog_interaction_create_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/interactions/dialog_interaction_create_packet.dart @@ -21,11 +21,12 @@ final class DialogInteractionCreatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final type = InteractionType.values.firstWhereOrNull((e) => e.value == message.payload['type']); + final type = InteractionType.values + .firstWhereOrNull((e) => e.value == message.payload['type']); if (type == InteractionType.modal) { - final interactionContext = InteractionContextType.values - .firstWhereOrNull((element) => element.value == message.payload['context']); + final interactionContext = InteractionContextType.values.firstWhereOrNull( + (element) => element.value == message.payload['context']); final Map parameters = List.from(message.payload['data']['components']).map((row) { @@ -48,7 +49,8 @@ final class DialogInteractionCreatePacket implements ListenablePacket { }; if ([event, ctx].contains(null)) { - logger.warn('Interaction context ${message.payload['context']} not found'); + logger.warn( + 'Interaction context ${message.payload['context']} not found'); return; } diff --git a/lib/infrastructure/internals/packets/listeners/interactions/select_interaction_create_packet.dart b/lib/infrastructure/internals/packets/listeners/interactions/select_interaction_create_packet.dart index f056e0e6..3993f40a 100644 --- a/lib/infrastructure/internals/packets/listeners/interactions/select_interaction_create_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/interactions/select_interaction_create_packet.dart @@ -26,15 +26,16 @@ final class SelectInteractionCreatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final type = InteractionType.values.firstWhereOrNull((e) => e.value == message.payload['type']); + final type = InteractionType.values + .firstWhereOrNull((e) => e.value == message.payload['type']); - final componentType = ComponentType.values - .firstWhereOrNull((e) => e.value == message.payload['data']['component_type']); + final componentType = ComponentType.values.firstWhereOrNull( + (e) => e.value == message.payload['data']['component_type']); if (type == InteractionType.messageComponent && ComponentType.selectMenus.contains(componentType)) { - final selectMenuType = ComponentType.values - .firstWhereOrNull((e) => e.value == message.payload['data']['component_type']); + final selectMenuType = ComponentType.values.firstWhereOrNull( + (e) => e.value == message.payload['data']['component_type']); final ctx = await switch (message.payload['guild_id']) { String() => ServerSelectContext.fromMap(marshaller, message.payload), @@ -56,8 +57,8 @@ final class SelectInteractionCreatePacket implements ListenablePacket { } } - Future _dispatchChannelSelectMenu( - SelectContext ctx, Map payload, DispatchEvent dispatch) async { + Future _dispatchChannelSelectMenu(SelectContext ctx, + Map payload, DispatchEvent dispatch) async { final resolvedData = payload['data']['resolved']; final channelIds = Map.from(resolvedData['channels']).keys; @@ -66,7 +67,8 @@ final class SelectInteractionCreatePacket implements ListenablePacket { final cacheKey = marshaller.cacheKey.channel(Snowflake(id)); final rawChannel = await marshaller.cache.getOrFail(cacheKey); - return marshaller.serializers.channels.serialize(rawChannel) as Future; + return marshaller.serializers.channels.serialize(rawChannel) + as Future; })); } @@ -83,13 +85,14 @@ final class SelectInteractionCreatePacket implements ListenablePacket { }; } - Future _dispatchRoleSelectMenu( - SelectContext ctx, Map payload, DispatchEvent dispatch) async { + Future _dispatchRoleSelectMenu(SelectContext ctx, + Map payload, DispatchEvent dispatch) async { final resolvedData = payload['data']['resolved']; final roleIds = Map.from(resolvedData['roles']).keys; final List resolvedRoles = await Future.wait(roleIds.map((id) async { - final cacheKey = marshaller.cacheKey.serverRole(payload['guild_id'], Snowflake(id)); + final cacheKey = + marshaller.cacheKey.serverRole(payload['guild_id'], Snowflake(id)); final rawRole = await marshaller.cache.getOrFail(cacheKey); return marshaller.serializers.role.serialize(rawRole); @@ -101,8 +104,8 @@ final class SelectInteractionCreatePacket implements ListenablePacket { constraint: (String? customId) => customId == ctx.customId); } - Future _dispatchUserSelectMenu( - SelectContext ctx, Map payload, DispatchEvent dispatch) async { + Future _dispatchUserSelectMenu(SelectContext ctx, + Map payload, DispatchEvent dispatch) async { final resolvedData = payload['data']['resolved']; final userIds = Map.from(resolvedData['users']).keys; @@ -135,8 +138,8 @@ final class SelectInteractionCreatePacket implements ListenablePacket { constraint: (String? customId) => customId == ctx.customId); } - Future _dispatchTextSelectMenu( - SelectContext ctx, Map payload, DispatchEvent dispatch) async { + Future _dispatchTextSelectMenu(SelectContext ctx, + Map payload, DispatchEvent dispatch) async { final List resolvedText = List.from(payload['data']['values']); return switch (ctx) { diff --git a/lib/infrastructure/internals/packets/listeners/message_create_packet.dart b/lib/infrastructure/internals/packets/listeners/message_create_packet.dart index 9cb1ae68..6d7f194a 100644 --- a/lib/infrastructure/internals/packets/listeners/message_create_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/message_create_packet.dart @@ -24,13 +24,18 @@ final class MessageCreatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - if (![MessageType.initial.value, MessageType.reply.value].contains(message.payload['type'])) { + if (![MessageType.initial.value, MessageType.reply.value] + .contains(message.payload['type'])) { return; } - final channel = await marshaller.dataStore.channel.getChannel(message.payload['channel_id']); + final channel = await marshaller.dataStore.channel + .getChannel(message.payload['channel_id']); - if ([ChannelType.guildPrivateThread.value, ChannelType.guildPublicThread.value].contains(channel!.type.value)) { + if ([ + ChannelType.guildPrivateThread.value, + ChannelType.guildPublicThread.value + ].contains(channel!.type.value)) { await sendThread(dispatch, message.payload); return; } @@ -41,12 +46,16 @@ final class MessageCreatePacket implements ListenablePacket { }; } - Future sendThread(DispatchEvent dispatch, Map json) async { - final server = await marshaller.dataStore.server.getServer(json['guild_id']); + Future sendThread( + DispatchEvent dispatch, Map json) async { + final server = + await marshaller.dataStore.server.getServer(json['guild_id']); final thread = server.threads.getOrFail(json['channel_id']); - final payload = await marshaller.serializers.serverMessage.normalize({...json, 'server_id': server.id.value}); - final message = await marshaller.serializers.serverMessage.serialize(payload); + final payload = await marshaller.serializers.serverMessage + .normalize({...json, 'server_id': server.id.value}); + final message = + await marshaller.serializers.serverMessage.serialize(payload); message.channel = thread; thread.messages.list.putIfAbsent(message.id, () => message); @@ -54,22 +63,30 @@ final class MessageCreatePacket implements ListenablePacket { dispatch(event: Event.serverMessageCreate, params: [message]); } - Future sendServerMessage(DispatchEvent dispatch, ServerChannel channel, Map json) async { - final server = await marshaller.dataStore.server.getServer(channel.serverId); + Future sendServerMessage(DispatchEvent dispatch, ServerChannel channel, + Map json) async { + final server = + await marshaller.dataStore.server.getServer(channel.serverId); - final payload = await marshaller.serializers.serverMessage.normalize({...json, 'server_id': server.id.value}); - final message = await marshaller.serializers.serverMessage.serialize(payload); + final payload = await marshaller.serializers.serverMessage + .normalize({...json, 'server_id': server.id.value}); + final message = + await marshaller.serializers.serverMessage.serialize(payload); message.channel = channel; switch (channel) { - case ServerTextChannel(): channel.messages.list.putIfAbsent(message.id, () => message); - case ServerVoiceChannel(): channel.messages.list.putIfAbsent(message.id, () => message); - case ServerAnnouncementChannel(): channel.messages.list.putIfAbsent(message.id, () => message); + case ServerTextChannel(): + channel.messages.list.putIfAbsent(message.id, () => message); + case ServerVoiceChannel(): + channel.messages.list.putIfAbsent(message.id, () => message); + case ServerAnnouncementChannel(): + channel.messages.list.putIfAbsent(message.id, () => message); } final rawServer = await marshaller.serializers.server.deserialize(server); - final rawMessage = await marshaller.serializers.serverMessage.deserialize(message); + final rawMessage = + await marshaller.serializers.serverMessage.deserialize(message); await marshaller.cache.putMany({ marshaller.cacheKey.server(server.id): rawServer, @@ -79,16 +96,20 @@ final class MessageCreatePacket implements ListenablePacket { dispatch(event: Event.serverMessageCreate, params: [message]); } - Future sendPrivateMessage(DispatchEvent dispatch, Channel channel, Map json) async { + Future sendPrivateMessage(DispatchEvent dispatch, Channel channel, + Map json) async { final payload = await marshaller.serializers.privateMessage.normalize(json); - final message = await marshaller.serializers.privateMessage.serialize(payload); + final message = + await marshaller.serializers.privateMessage.serialize(payload); if (channel is PrivateChannel) { message.channel = channel; channel.messages.list.putIfAbsent(message.id, () => message); - final rawChannel = await marshaller.serializers.channels.deserialize(channel); - final rawMessage = await marshaller.serializers.privateMessage.deserialize(message); + final rawChannel = + await marshaller.serializers.channels.deserialize(channel); + final rawMessage = + await marshaller.serializers.privateMessage.deserialize(message); await marshaller.cache.putMany({ marshaller.cacheKey.channel(channel.id): rawChannel, diff --git a/lib/infrastructure/internals/packets/listeners/presence_update_packet.dart b/lib/infrastructure/internals/packets/listeners/presence_update_packet.dart index c0ce738b..84ab6054 100644 --- a/lib/infrastructure/internals/packets/listeners/presence_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/presence_update_packet.dart @@ -17,11 +17,13 @@ final class PresenceUpdatePacket implements ListenablePacket { @override Future listen(ShardMessage message, DispatchEvent dispatch) async { - final server = await marshaller.dataStore.server.getServer(message.payload['guild_id']); - final memberCacheKey = marshaller.cacheKey.member(server.id, message.payload['user']['id']); + final server = await marshaller.dataStore.server + .getServer(message.payload['guild_id']); + final memberCacheKey = + marshaller.cacheKey.member(server.id, message.payload['user']['id']); - final member = await marshaller.dataStore.member - .getMember(memberId: message.payload['user']['id'], serverId: server.id); + final member = await marshaller.dataStore.member.getMember( + memberId: message.payload['user']['id'], serverId: server.id); final presence = Presence.fromJson(message.payload); member @@ -31,6 +33,7 @@ final class PresenceUpdatePacket implements ListenablePacket { final rawMember = await marshaller.serializers.member.deserialize(member); await marshaller.cache.put(memberCacheKey, rawMember); - dispatch(event: Event.serverPresenceUpdate, params: [member, server, presence]); + dispatch( + event: Event.serverPresenceUpdate, params: [member, server, presence]); } } diff --git a/lib/infrastructure/internals/packets/listeners/ready_packet.dart b/lib/infrastructure/internals/packets/listeners/ready_packet.dart index 7b62a505..42881419 100644 --- a/lib/infrastructure/internals/packets/listeners/ready_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/ready_packet.dart @@ -28,7 +28,7 @@ final class ReadyPacket implements ListenablePacket { logger.trace(jsonEncode(message.payload)); - if(!isAlreadyUsed) { + if (!isAlreadyUsed) { await interactionManager.registerGlobal(bot); isAlreadyUsed = true; } diff --git a/lib/infrastructure/internals/packets/listeners/thread_create_packet.dart b/lib/infrastructure/internals/packets/listeners/thread_create_packet.dart index 9d46a858..3f39b9cc 100644 --- a/lib/infrastructure/internals/packets/listeners/thread_create_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/thread_create_packet.dart @@ -20,7 +20,8 @@ final class ThreadCreatePacket implements ListenablePacket { Future listen(ShardMessage message, DispatchEvent dispatch) async { final payload = message.payload; - final server = await marshaller.dataStore.server.getServer(payload['guild_id']); + final server = + await marshaller.dataStore.server.getServer(payload['guild_id']); final threadRaw = await marshaller.serializers.thread.normalize(payload); final thread = await marshaller.serializers.thread.serialize(threadRaw); @@ -31,10 +32,12 @@ final class ThreadCreatePacket implements ListenablePacket { marshaller.cache.put(serverKey, serverRaw); - final parentChannel = server.channels.list[Snowflake(thread.channelId)] as ServerTextChannel; + final parentChannel = + server.channels.list[Snowflake(thread.channelId)] as ServerTextChannel; parentChannel.threads.add(thread); - final parentChannelRaw = await marshaller.serializers.channels.deserialize(parentChannel); + final parentChannelRaw = + await marshaller.serializers.channels.deserialize(parentChannel); final parentChannelKey = marshaller.cacheKey.channel(parentChannel.id); marshaller.cache.put(parentChannelKey, parentChannelRaw); diff --git a/lib/infrastructure/internals/packets/listeners/thread_delete_packet.dart b/lib/infrastructure/internals/packets/listeners/thread_delete_packet.dart index e764bcdd..62cef86a 100644 --- a/lib/infrastructure/internals/packets/listeners/thread_delete_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/thread_delete_packet.dart @@ -18,7 +18,8 @@ final class ThreadDeletePacket implements ListenablePacket { Future listen(ShardMessage message, DispatchEvent dispatch) async { final payload = message.payload; - final server = await marshaller.dataStore.server.getServer(payload['guild_id']); + final server = + await marshaller.dataStore.server.getServer(payload['guild_id']); final threadCacheKey = marshaller.cacheKey.thread(payload['id']); final threadRaw = await marshaller.cache.getOrFail(threadCacheKey); diff --git a/lib/infrastructure/internals/packets/listeners/thread_list_sync_packet.dart b/lib/infrastructure/internals/packets/listeners/thread_list_sync_packet.dart index d3c7ac1c..ee89df78 100644 --- a/lib/infrastructure/internals/packets/listeners/thread_list_sync_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/thread_list_sync_packet.dart @@ -18,7 +18,8 @@ final class ThreadListSyncPacket implements ListenablePacket { Future listen(ShardMessage message, DispatchEvent dispatch) async { final payload = message.payload; - final server = await marshaller.dataStore.server.getServer(payload['guild_id']); + final server = + await marshaller.dataStore.server.getServer(payload['guild_id']); final threadChannels = payload['threads'] as List>; final threads = await threadChannels.map((element) async { diff --git a/lib/infrastructure/internals/packets/listeners/thread_member_update_packet.dart b/lib/infrastructure/internals/packets/listeners/thread_member_update_packet.dart index 6afa44a7..14356ec6 100644 --- a/lib/infrastructure/internals/packets/listeners/thread_member_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/thread_member_update_packet.dart @@ -21,9 +21,12 @@ final class ThreadMemberUpdatePacket implements ListenablePacket { Future listen(ShardMessage message, DispatchEvent dispatch) async { final payload = message.payload; - final server = await marshaller.dataStore.server.getServer(payload['guild_id']); - final thread = await marshaller.dataStore.channel.getThread(Snowflake(payload['id'])) as ThreadChannel; - final member = await marshaller.dataStore.member.getMember(memberId: Snowflake(payload['user_id']), serverId: server.id); + final server = + await marshaller.dataStore.server.getServer(payload['guild_id']); + final thread = await marshaller.dataStore.channel + .getThread(Snowflake(payload['id'])) as ThreadChannel; + final member = await marshaller.dataStore.member.getMember( + memberId: Snowflake(payload['user_id']), serverId: server.id); thread.members[member.id] = member; server.threads.add(thread); @@ -33,14 +36,18 @@ final class ThreadMemberUpdatePacket implements ListenablePacket { marshaller.cache.put(serverKey, serverRaw); - final parentChannel = server.channels.list[Snowflake(thread.channelId)] as ServerTextChannel; + final parentChannel = + server.channels.list[Snowflake(thread.channelId)] as ServerTextChannel; parentChannel.threads.add(thread); - final parentChannelRaw = await marshaller.serializers.channels.deserialize(parentChannel); + final parentChannelRaw = + await marshaller.serializers.channels.deserialize(parentChannel); final parentChannelKey = marshaller.cacheKey.channel(parentChannel.id); marshaller.cache.put(parentChannelKey, parentChannelRaw); - dispatch(event: Event.serverThreadMemberUpdate, params: [thread, server, member]); + dispatch( + event: Event.serverThreadMemberUpdate, + params: [thread, server, member]); } } diff --git a/lib/infrastructure/internals/packets/listeners/thread_members_update_packet.dart b/lib/infrastructure/internals/packets/listeners/thread_members_update_packet.dart index a50eea64..8b50b157 100644 --- a/lib/infrastructure/internals/packets/listeners/thread_members_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/thread_members_update_packet.dart @@ -21,23 +21,31 @@ final class ThreadMembersUpdatePacket implements ListenablePacket { Future listen(ShardMessage message, DispatchEvent dispatch) async { final payload = message.payload; - final server = await marshaller.dataStore.server.getServer(payload['guild_id']); - final thread = await marshaller.dataStore.channel.getThread(Snowflake(payload['id'])) as ThreadChannel; + final server = + await marshaller.dataStore.server.getServer(payload['guild_id']); + final thread = await marshaller.dataStore.channel + .getThread(Snowflake(payload['id'])) as ThreadChannel; final membersAdded = payload['added_members'] ?? []; final membersRemovedIds = payload['removed_member_ids'] ?? []; for (final memberThread in membersAdded) { - final member = await marshaller.dataStore.member.getMember(serverId: payload['guild_id'], memberId: Snowflake(memberThread['user_id'])); + final member = await marshaller.dataStore.member.getMember( + serverId: payload['guild_id'], + memberId: Snowflake(memberThread['user_id'])); thread.members.putIfAbsent(member.id, () => member); - dispatch(event: Event.serverThreadMemberAdd, params: [thread, server, member]); + dispatch( + event: Event.serverThreadMemberAdd, params: [thread, server, member]); } for (final memberId in membersRemovedIds) { - final member = await marshaller.dataStore.member.getMember(serverId: payload['guild_id'], memberId: Snowflake(memberId)); + final member = await marshaller.dataStore.member.getMember( + serverId: payload['guild_id'], memberId: Snowflake(memberId)); thread.members.remove(Snowflake(memberId)); - dispatch(event: Event.serverThreadMemberRemove, params: [thread, server, member]); + dispatch( + event: Event.serverThreadMemberRemove, + params: [thread, server, member]); } final serverRaw = await marshaller.serializers.server.deserialize(server); @@ -45,10 +53,12 @@ final class ThreadMembersUpdatePacket implements ListenablePacket { marshaller.cache.put(serverKey, serverRaw); - final parentChannel = server.channels.list[Snowflake(thread.channelId)] as ServerTextChannel; + final parentChannel = + server.channels.list[Snowflake(thread.channelId)] as ServerTextChannel; parentChannel.threads.add(thread); - final parentChannelRaw = await marshaller.serializers.channels.deserialize(parentChannel); + final parentChannelRaw = + await marshaller.serializers.channels.deserialize(parentChannel); final parentChannelKey = marshaller.cacheKey.channel(parentChannel.id); marshaller.cache.put(parentChannelKey, parentChannelRaw); diff --git a/lib/infrastructure/internals/packets/listeners/thread_update_packet.dart b/lib/infrastructure/internals/packets/listeners/thread_update_packet.dart index bb5131e7..a7fdccb3 100644 --- a/lib/infrastructure/internals/packets/listeners/thread_update_packet.dart +++ b/lib/infrastructure/internals/packets/listeners/thread_update_packet.dart @@ -20,7 +20,8 @@ final class ThreadUpdatePacket implements ListenablePacket { Future listen(ShardMessage message, DispatchEvent dispatch) async { final payload = message.payload; - final server = await marshaller.dataStore.server.getServer(payload['guild_id']); + final server = + await marshaller.dataStore.server.getServer(payload['guild_id']); final threadCacheKey = marshaller.cacheKey.thread(payload['id']); final beforeRaw = await marshaller.cache.getOrFail(threadCacheKey); @@ -38,11 +39,13 @@ final class ThreadUpdatePacket implements ListenablePacket { after ..server = server - ..parentChannel = server.channels.list[Snowflake(after.channelId)] as ServerTextChannel; + ..parentChannel = + server.channels.list[Snowflake(after.channelId)] as ServerTextChannel; before ..server = server - ..parentChannel = server.channels.list[Snowflake(before.channelId)] as ServerTextChannel; + ..parentChannel = server.channels.list[Snowflake(before.channelId)] + as ServerTextChannel; dispatch(event: Event.serverThreadUpdate, params: [before, after, server]); } diff --git a/lib/infrastructure/internals/packets/packet_dispatcher.dart b/lib/infrastructure/internals/packets/packet_dispatcher.dart index 616d19e1..8936d067 100644 --- a/lib/infrastructure/internals/packets/packet_dispatcher.dart +++ b/lib/infrastructure/internals/packets/packet_dispatcher.dart @@ -7,7 +7,8 @@ import 'package:mineral/infrastructure/kernel/kernel.dart'; import 'package:rxdart/rxdart.dart'; abstract interface class PacketDispatcherContract { - void listen(PacketType packet, Function(ShardMessage, DispatchEvent) listener); + void listen( + PacketType packet, Function(ShardMessage, DispatchEvent) listener); void dispatch(dynamic payload); @@ -21,10 +22,14 @@ final class PacketDispatcher implements PacketDispatcherContract { PacketDispatcher(this._kernel); @override - void listen(PacketType packet, Function(ShardMessage, DispatchEvent) listener) { - _packets.stream.where((event) => event.type == packet.name).listen((ShardMessage message) { + void listen( + PacketType packet, Function(ShardMessage, DispatchEvent) listener) { + _packets.stream + .where((event) => event.type == packet.name) + .listen((ShardMessage message) { _kernel.logger.trace(jsonEncode(message.serialize())); - Function.apply(listener, [message, _kernel.eventListener.dispatcher.dispatch]); + Function.apply( + listener, [message, _kernel.eventListener.dispatcher.dispatch]); }); } diff --git a/lib/infrastructure/internals/packets/packet_listener.dart b/lib/infrastructure/internals/packets/packet_listener.dart index 771e1adc..4a5378c1 100644 --- a/lib/infrastructure/internals/packets/packet_listener.dart +++ b/lib/infrastructure/internals/packets/packet_listener.dart @@ -46,7 +46,8 @@ final class PacketListener implements PacketListenerContract { late final KernelContract kernel; - void subscribe(ListenablePacket Function(LoggerContract, MarshallerContract) factory) { + void subscribe( + ListenablePacket Function(LoggerContract, MarshallerContract) factory) { final packet = factory(kernel.logger, kernel.marshaller); dispatcher.listen(packet.packetType, packet.listen); } diff --git a/lib/infrastructure/internals/wss/constants/op_code.dart b/lib/infrastructure/internals/wss/constants/op_code.dart index 28943aab..18e48cd1 100644 --- a/lib/infrastructure/internals/wss/constants/op_code.dart +++ b/lib/infrastructure/internals/wss/constants/op_code.dart @@ -14,5 +14,5 @@ enum OpCode { guildSync(12); final int value; - const OpCode (this.value); + const OpCode(this.value); } diff --git a/lib/infrastructure/internals/wss/constants/shard_disconnect_error.dart b/lib/infrastructure/internals/wss/constants/shard_disconnect_error.dart index 44edaa77..19e1b428 100644 --- a/lib/infrastructure/internals/wss/constants/shard_disconnect_error.dart +++ b/lib/infrastructure/internals/wss/constants/shard_disconnect_error.dart @@ -10,20 +10,20 @@ enum ShardDisconnectError { serviceRestart(1012, 'Service restart', false), tryAgainLater(1013, 'Try again later', false), invalidTls(1015, 'Invalid TLS', false), - unknownError(4000, 'Unknown error', true), - unknownOpCode(4001, 'Unknown opcode', true), - decodeError(4002, 'Decode error', true), - notAuthenticated(4003, 'Not authenticated', true), - authenticationFailed(4004, 'Authentication failed', false), - alreadyAuthenticated(4005, 'Already authenticated', true), - invalidSequence(4007, 'Invalid sequence', true), - rateLimited(4008, 'Rate limited', true), - sessionTimeout(4009, 'Session timed out', true), - invalidShard(4010, 'Invalid shard', false), - shardingRequired(4011, 'Sharding required', false), - invalidApiVersion(4012, 'Invalid API version', false), - invalidIntents(4013, 'Invalid intent(s)', false), - disallowedIntents(4014, 'Disallowed intent(s)', false); + unknownError(4000, 'Unknown error', true), + unknownOpCode(4001, 'Unknown opcode', true), + decodeError(4002, 'Decode error', true), + notAuthenticated(4003, 'Not authenticated', true), + authenticationFailed(4004, 'Authentication failed', false), + alreadyAuthenticated(4005, 'Already authenticated', true), + invalidSequence(4007, 'Invalid sequence', true), + rateLimited(4008, 'Rate limited', true), + sessionTimeout(4009, 'Session timed out', true), + invalidShard(4010, 'Invalid shard', false), + shardingRequired(4011, 'Sharding required', false), + invalidApiVersion(4012, 'Invalid API version', false), + invalidIntents(4013, 'Invalid intent(s)', false), + disallowedIntents(4014, 'Disallowed intent(s)', false); final int code; final String message; diff --git a/lib/infrastructure/internals/wss/dispatchers/shard_data.dart b/lib/infrastructure/internals/wss/dispatchers/shard_data.dart index 4920286b..76c333e9 100644 --- a/lib/infrastructure/internals/wss/dispatchers/shard_data.dart +++ b/lib/infrastructure/internals/wss/dispatchers/shard_data.dart @@ -19,7 +19,8 @@ final class ShardDataImpl implements ShardData { @override void dispatch(WebsocketMessage message) { - if (message.content case ShardMessage(:final type, :final payload) when type == 'READY') { + if (message.content case ShardMessage(:final type, :final payload) + when type == 'READY') { _shard.authentication.setupRequirements(payload); } diff --git a/lib/infrastructure/internals/wss/dispatchers/shard_network_error.dart b/lib/infrastructure/internals/wss/dispatchers/shard_network_error.dart index 8047a0a9..d0f1957d 100644 --- a/lib/infrastructure/internals/wss/dispatchers/shard_network_error.dart +++ b/lib/infrastructure/internals/wss/dispatchers/shard_network_error.dart @@ -29,8 +29,11 @@ final class ShardNetworkErrorImpl implements ShardNetworkError { .where((element) => element.code == payload) .firstOrNull; - if (error case ShardDisconnectError(canBeReconnected: final canBeReconnected)) { - return canBeReconnected ? shard.authentication.resume() : shard.authentication.reconnect(); + if (error + case ShardDisconnectError(canBeReconnected: final canBeReconnected)) { + return canBeReconnected + ? shard.authentication.resume() + : shard.authentication.reconnect(); } } } diff --git a/lib/infrastructure/internals/wss/shard.dart b/lib/infrastructure/internals/wss/shard.dart index f69b869d..f4ceaff5 100644 --- a/lib/infrastructure/internals/wss/shard.dart +++ b/lib/infrastructure/internals/wss/shard.dart @@ -84,12 +84,14 @@ final class Shard implements ShardContract { return message; }) ..add((message) async { - message.content = ShardMessageImpl.of(jsonDecode(message.originalContent)); + message.content = + ShardMessageImpl.of(jsonDecode(message.originalContent)); return message; }); client.listen((message) { - if (message.content case ShardMessage(opCode: final code, payload: final payload)) { + if (message.content + case ShardMessage(opCode: final code, payload: final payload)) { switch (code) { case OpCode.hello: authentication.identify(payload); @@ -100,7 +102,8 @@ final class Shard implements ShardContract { case OpCode.invalidSession: authentication.resume(); case OpCode.dispatch: - if ([PacketType.ready.name, PacketType.guildCreate.name].contains((message.content as ShardMessage).type)) { + if ([PacketType.ready.name, PacketType.guildCreate.name] + .contains((message.content as ShardMessage).type)) { onceEventQueue.add(jsonDecode(message.originalContent)); } diff --git a/lib/infrastructure/internals/wss/shard_message.dart b/lib/infrastructure/internals/wss/shard_message.dart index 721924fd..fb35989a 100644 --- a/lib/infrastructure/internals/wss/shard_message.dart +++ b/lib/infrastructure/internals/wss/shard_message.dart @@ -26,11 +26,15 @@ final class ShardMessageImpl implements ShardMessage { final T payload; ShardMessageImpl( - {required this.type, required this.opCode, required this.sequence, required this.payload}); + {required this.type, + required this.opCode, + required this.sequence, + required this.payload}); factory ShardMessageImpl.of(Map message) => ShardMessageImpl( type: message['t'], - opCode: OpCode.values.firstWhere((element) => element.value == message['op']), + opCode: + OpCode.values.firstWhere((element) => element.value == message['op']), sequence: message['s'], payload: message['d']); diff --git a/lib/infrastructure/kernel/kernel.dart b/lib/infrastructure/kernel/kernel.dart index aa82cff4..adc66f7b 100644 --- a/lib/infrastructure/kernel/kernel.dart +++ b/lib/infrastructure/kernel/kernel.dart @@ -118,7 +118,8 @@ final class Kernel implements KernelContract { Future> getWebsocketEndpoint() async { final response = await httpClient.get('/gateway/bot'); return switch (response.statusCode) { - int() when httpClient.status.isSuccess(response.statusCode) => response.body, + int() when httpClient.status.isSuccess(response.statusCode) => + response.body, int() when httpClient.status.isError(response.statusCode) => throw TokenException('This token is invalid or revocated !'), _ => throw TokenException('This token is invalid or revocated !'), @@ -135,7 +136,8 @@ final class Kernel implements KernelContract { } if (Isolate.current.debugName == 'main') { - final packageFile = File(path.join(Directory.current.path, 'pubspec.yaml')); + final packageFile = + File(path.join(Directory.current.path, 'pubspec.yaml')); final packageFileContent = await packageFile.readAsString(); final package = loadYaml(packageFileContent); @@ -198,7 +200,8 @@ final class Kernel implements KernelContract { } if (useHmr) { - hmr = HotModuleReloading(_devPort, watcherConfig, this, createShards, shards); + hmr = HotModuleReloading( + _devPort, watcherConfig, this, createShards, shards); await hmr?.spawn(); } else { createShards(); @@ -206,11 +209,14 @@ final class Kernel implements KernelContract { } Future createShards() async { - final {'url': String endpoint, 'shards': int shardCount} = await getWebsocketEndpoint(); + final {'url': String endpoint, 'shards': int shardCount} = + await getWebsocketEndpoint(); for (int i = 0; i < (config.shardCount ?? shardCount); i++) { - final shard = - Shard(shardName: 'shard #$i', url: '$endpoint/?v=${config.version}', kernel: this); + final shard = Shard( + shardName: 'shard #$i', + url: '$endpoint/?v=${config.version}', + kernel: this); shards.putIfAbsent(i, () => shard); await shard.init(); diff --git a/lib/infrastructure/kernel/mineral_client.dart b/lib/infrastructure/kernel/mineral_client.dart index 4dbf7008..809230d2 100644 --- a/lib/infrastructure/kernel/mineral_client.dart +++ b/lib/infrastructure/kernel/mineral_client.dart @@ -52,8 +52,7 @@ final class MineralClient implements MineralClientContract { _kernel.eventListener.listen( event: instance.event, handle: (instance as dynamic).handle as Function, - customId: instance.customId - ); + customId: instance.customId); } } diff --git a/lib/infrastructure/services/http/http_client.dart b/lib/infrastructure/services/http/http_client.dart index 52dc570e..29e01ee1 100644 --- a/lib/infrastructure/services/http/http_client.dart +++ b/lib/infrastructure/services/http/http_client.dart @@ -53,7 +53,8 @@ final class HttpClient implements HttpClientContract { } @override - Future> get(String endpoint, {HttpRequestOption? option}) async { + Future> get(String endpoint, + {HttpRequestOption? option}) async { return _request('GET', endpoint, option, null); } @@ -81,8 +82,8 @@ final class HttpClient implements HttpClientContract { return _request(method, endpoint, option, body); } - Future> _request( - String method, String endpoint, HttpRequestOption? option, Object? body) async { + Future> _request(String method, String endpoint, + HttpRequestOption? option, Object? body) async { String url = '${config.baseUrl}$endpoint'; if (option case HttpRequestOption(queryParameters: final params)) { @@ -105,7 +106,8 @@ final class HttpClient implements HttpClientContract { ..headers.addAll(_serializeHeaders(request.headers)) ..body = request.body != null ? jsonEncode(request.body) : ''; - final http.StreamedResponse streamedResponse = await _client.send(httpRequest); + final http.StreamedResponse streamedResponse = + await _client.send(httpRequest); final http.Response res = await http.Response.fromStream(streamedResponse); Response response = ResponseImpl.fromHttpResponse(res); @@ -118,7 +120,9 @@ final class HttpClient implements HttpClientContract { } Map _serializeHeaders(Set
headers) { - return headers - .fold({}, (previousValue, element) => {...previousValue, element.key: element.value}); + return headers.fold( + {}, + (previousValue, element) => + {...previousValue, element.key: element.value}); } } diff --git a/lib/infrastructure/services/http/http_client_config.dart b/lib/infrastructure/services/http/http_client_config.dart index 9b4f2c4b..ab87c38d 100644 --- a/lib/infrastructure/services/http/http_client_config.dart +++ b/lib/infrastructure/services/http/http_client_config.dart @@ -13,5 +13,6 @@ final class HttpClientConfigImpl implements HttpClientConfig { @override final Set
headers; - HttpClientConfigImpl({required this.baseUrl, Set
? headers}) : headers = headers ?? {}; + HttpClientConfigImpl({required this.baseUrl, Set
? headers}) + : headers = headers ?? {}; } diff --git a/lib/infrastructure/services/http/http_request_option.dart b/lib/infrastructure/services/http/http_request_option.dart index 69a51af1..28f0882d 100644 --- a/lib/infrastructure/services/http/http_request_option.dart +++ b/lib/infrastructure/services/http/http_request_option.dart @@ -13,5 +13,6 @@ final class HttpRequestOptionImpl implements HttpRequestOption { @override final Map queryParameters; - HttpRequestOptionImpl({required this.headers, this.queryParameters = const {}}); + HttpRequestOptionImpl( + {required this.headers, this.queryParameters = const {}}); } diff --git a/lib/infrastructure/services/http/response.dart b/lib/infrastructure/services/http/response.dart index 1364a405..f16c59ae 100644 --- a/lib/infrastructure/services/http/response.dart +++ b/lib/infrastructure/services/http/response.dart @@ -50,7 +50,9 @@ final class ResponseImpl implements Response { factory ResponseImpl.fromHttpResponse(http.Response response) { return ResponseImpl._( statusCode: response.statusCode, - headers: response.headers.entries.map((entry) => Header(entry.key, entry.value)).toSet(), + headers: response.headers.entries + .map((entry) => Header(entry.key, entry.value)) + .toSet(), bodyString: response.body, body: response.body.isNotEmpty ? jsonDecode(response.body) : {}, uri: response.request!.url, diff --git a/lib/infrastructure/services/http/type/response_code.dart b/lib/infrastructure/services/http/type/response_code.dart index 23423935..50dc9584 100644 --- a/lib/infrastructure/services/http/type/response_code.dart +++ b/lib/infrastructure/services/http/type/response_code.dart @@ -26,22 +26,18 @@ enum ResponseCode { } static List get errorsCodes => [ - badRequest, - unauthorized, - forbidden, - notFound, - methodNotAllowed, - internalServerError, - badGateway, - serviceUnavailable, - gatewayTimeout, - unknown - ]; + badRequest, + unauthorized, + forbidden, + notFound, + methodNotAllowed, + internalServerError, + badGateway, + serviceUnavailable, + gatewayTimeout, + unknown + ]; - static List get successCodes => [ - success, - created, - accepted, - noContent - ]; -} \ No newline at end of file + static List get successCodes => + [success, created, accepted, noContent]; +} diff --git a/lib/infrastructure/services/logger/logger.dart b/lib/infrastructure/services/logger/logger.dart index f1043c5a..a47780a9 100644 --- a/lib/infrastructure/services/logger/logger.dart +++ b/lib/infrastructure/services/logger/logger.dart @@ -47,7 +47,8 @@ final class Logger implements LoggerContract { logging.Logger.root.onRecord.listen((record) { final time = '[${DateFormat.Hms().format(record.time)}]'; - List makeMessage(String messageType, Color messageColor, List message) { + List makeMessage( + String messageType, Color messageColor, List message) { return [ SetStyles(Style.foreground(Color.brightBlack)), Print(time), @@ -62,12 +63,18 @@ final class Logger implements LoggerContract { } final message = switch (record.level) { - logging.Level.FINEST => makeMessage('trace', Color.white, - [SetStyles(Style.foreground(Color.brightBlack)), Print(record.message)]), - logging.Level.SHOUT => makeMessage('fatal', Color.brightRed, [Print(record.message)]), - logging.Level.SEVERE => makeMessage('error', Color.red, [Print(record.message)]), - logging.Level.WARNING => makeMessage('warn', Color.yellow, [Print(record.message)]), - logging.Level.INFO => makeMessage('info', Color.fromRGB(140, 169, 238), [Print(record.message)]), + logging.Level.FINEST => makeMessage('trace', Color.white, [ + SetStyles(Style.foreground(Color.brightBlack)), + Print(record.message) + ]), + logging.Level.SHOUT => + makeMessage('fatal', Color.brightRed, [Print(record.message)]), + logging.Level.SEVERE => + makeMessage('error', Color.red, [Print(record.message)]), + logging.Level.WARNING => + makeMessage('warn', Color.yellow, [Print(record.message)]), + logging.Level.INFO => makeMessage( + 'info', Color.fromRGB(140, 169, 238), [Print(record.message)]), _ => makeMessage('unknown', Color.blue, [Print(record.message)]), }; @@ -104,9 +111,11 @@ final class Logger implements LoggerContract { extension on List { void writeWithoutAnsi() { for (final sequence in this) { - switch(sequence) { - case Print(:final text): stdout.write(text); - case AsciiControl(:final writeAnsiString): writeAnsiString(stdout); + switch (sequence) { + case Print(:final text): + stdout.write(text); + case AsciiControl(:final writeAnsiString): + writeAnsiString(stdout); default: } } diff --git a/lib/infrastructure/services/placeholder/env_placeholder.dart b/lib/infrastructure/services/placeholder/env_placeholder.dart index eb8efead..91bb4a65 100644 --- a/lib/infrastructure/services/placeholder/env_placeholder.dart +++ b/lib/infrastructure/services/placeholder/env_placeholder.dart @@ -35,7 +35,7 @@ final class EnvPlaceholder implements PlaceholderContract { }; return acc - .replaceAll('{${element.key}}', finalValue) - .replaceAll('{{ ${element.key} }}', finalValue); + .replaceAll('{${element.key}}', finalValue) + .replaceAll('{{ ${element.key} }}', finalValue); }); } diff --git a/lib/infrastructure/services/placeholder/placeholder.dart b/lib/infrastructure/services/placeholder/placeholder.dart index b3bfaa29..eb4d6a05 100644 --- a/lib/infrastructure/services/placeholder/placeholder.dart +++ b/lib/infrastructure/services/placeholder/placeholder.dart @@ -50,7 +50,9 @@ class Placeholder implements PlaceholderContract { String finalValue = value; if (values != null) { final currentValues = Map.from(values.map((key, value) => - identifier != null ? MapEntry('$identifier.$key', value) : MapEntry(key, value))); + identifier != null + ? MapEntry('$identifier.$key', value) + : MapEntry(key, value))); finalValue = _replace(value, currentValues); } @@ -67,7 +69,8 @@ class Placeholder implements PlaceholderContract { }; return acc - .replaceAllMapped(RegExp(r'\{\{\s*([^}]*)\s*\}\}'), (Match m) => '{{${m[1]?.trim()}}}') + .replaceAllMapped(RegExp(r'\{\{\s*([^}]*)\s*\}\}'), + (Match m) => '{{${m[1]?.trim()}}}') .replaceAll('{{${element.key}}}', finalValue); }); } diff --git a/lib/infrastructure/services/wss/interceptor.dart b/lib/infrastructure/services/wss/interceptor.dart index 57bc9ecb..31ea7cb2 100644 --- a/lib/infrastructure/services/wss/interceptor.dart +++ b/lib/infrastructure/services/wss/interceptor.dart @@ -1,8 +1,10 @@ import 'package:mineral/infrastructure/services/wss/websocket_message.dart'; import 'package:mineral/infrastructure/services/wss/websocket_requested_message.dart'; -typedef MessageInterceptor = Future Function(WebsocketMessage); -typedef RequestInterceptor = Future Function(WebsocketRequestedMessage); +typedef MessageInterceptor = Future Function( + WebsocketMessage); +typedef RequestInterceptor = Future Function( + WebsocketRequestedMessage); abstract interface class Interceptor { List get message; diff --git a/lib/infrastructure/services/wss/websocket_client.dart b/lib/infrastructure/services/wss/websocket_client.dart index 6e1f3d71..fe1175a1 100644 --- a/lib/infrastructure/services/wss/websocket_client.dart +++ b/lib/infrastructure/services/wss/websocket_client.dart @@ -61,7 +61,11 @@ final class WebsocketClientImpl implements WebsocketClient { if (_onError != null) { stream!.handleError((err) { - _onError({'error': err, 'code': _channel?.closeCode, 'reason': _channel?.closeReason}); + _onError({ + 'error': err, + 'code': _channel?.closeCode, + 'reason': _channel?.closeReason + }); }); } @@ -78,7 +82,11 @@ final class WebsocketClientImpl implements WebsocketClient { } } on io.WebSocketException catch (err) { print(err); - _onError!({'error': err, 'code': _channel?.closeCode, 'reason': _channel?.closeReason}); + _onError!({ + 'error': err, + 'code': _channel?.closeCode, + 'reason': _channel?.closeReason + }); } } @@ -94,8 +102,11 @@ final class WebsocketClientImpl implements WebsocketClient { } Future _handleMessage(callback, dynamic message) async { - final interceptedMessage = await _handleMessageInterceptors(WebsocketMessageImpl( - channelName: name, originalContent: message as String, content: message)); + final interceptedMessage = await _handleMessageInterceptors( + WebsocketMessageImpl( + channelName: name, + originalContent: message as String, + content: message)); callback(interceptedMessage); } @@ -113,7 +124,8 @@ final class WebsocketClientImpl implements WebsocketClient { } } - Future _handleMessageInterceptors(WebsocketMessage message) async { + Future _handleMessageInterceptors( + WebsocketMessage message) async { for (final interceptor in interceptor.message) { message = await interceptor(message); } diff --git a/lib/infrastructure/services/wss/websocket_message.dart b/lib/infrastructure/services/wss/websocket_message.dart index b73beafc..81599af0 100644 --- a/lib/infrastructure/services/wss/websocket_message.dart +++ b/lib/infrastructure/services/wss/websocket_message.dart @@ -22,5 +22,7 @@ final class WebsocketMessageImpl implements WebsocketMessage { T content; WebsocketMessageImpl( - {required this.channelName, required this.originalContent, required this.content}); + {required this.channelName, + required this.originalContent, + required this.content}); } diff --git a/lib/infrastructure/services/wss/websocket_requested_message.dart b/lib/infrastructure/services/wss/websocket_requested_message.dart index 39e16e5d..4c5a2173 100644 --- a/lib/infrastructure/services/wss/websocket_requested_message.dart +++ b/lib/infrastructure/services/wss/websocket_requested_message.dart @@ -16,5 +16,6 @@ final class WebsocketRequestedMessageImpl implements WebsocketRequestedMessage { @override final String content; - WebsocketRequestedMessageImpl({required this.channelName, required this.content}); + WebsocketRequestedMessageImpl( + {required this.channelName, required this.content}); } diff --git a/test/core_test.dart b/test/core_test.dart index 72dc5e6b..f554e2e7 100644 --- a/test/core_test.dart +++ b/test/core_test.dart @@ -1,5 +1,5 @@ import './internals/ioc.dart' as ioc_test; -void main () { +void main() { ioc_test.main(); } diff --git a/test/internals/ioc.dart b/test/internals/ioc.dart index 0892a508..9b02336a 100644 --- a/test/internals/ioc.dart +++ b/test/internals/ioc.dart @@ -4,7 +4,9 @@ import 'package:test/test.dart'; abstract interface class AbstractClass {} final class FooWithoutAbstract {} + final class Foo implements AbstractClass {} + final class Bar implements AbstractClass {} void main() {