Skip to content

Commit

Permalink
Improve Injector implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
l7ssha committed Oct 9, 2024
1 parent 00579de commit 03d2044
Show file tree
Hide file tree
Showing 14 changed files with 186 additions and 60 deletions.
15 changes: 11 additions & 4 deletions bin/running_on_dart.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,9 @@ void main() async {
],
));

final db = DatabaseService();
await db.awaitReady();

Injector.appInstance
..registerSingleton(() => client)
..registerSingleton(() => db)
..registerSingleton(() => DatabaseService())
..registerSingleton(() => FeatureSettingsRepository())
..registerSingleton(() => JellyfinConfigRepository())
..registerSingleton(() => ReminderRepository())
Expand All @@ -74,4 +71,14 @@ void main() async {
..registerSingleton(() => TagModule())
..registerSingleton(() => DocsModule())
..registerSingleton(() => JellyfinModule());

await Injector.appInstance.get<DatabaseService>().init();
await Injector.appInstance.get<JellyfinModule>().init();
await Injector.appInstance.get<DocsModule>().init();
await Injector.appInstance.get<TagModule>().init();
await Injector.appInstance.get<ModLogsModule>().init();
await Injector.appInstance.get<ReminderModule>().init();
await Injector.appInstance.get<JoinLogsModule>().init();
await Injector.appInstance.get<PoopNameModule>().init();
await Injector.appInstance.get<BotStartDuration>().init();
}
37 changes: 19 additions & 18 deletions lib/src/commands/jellyfin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import 'package:running_on_dart/running_on_dart.dart';
import 'package:running_on_dart/src/checks.dart';
import 'package:running_on_dart/src/models/jellyfin_config.dart';
import 'package:running_on_dart/src/repository/jellyfin_config.dart';
import 'package:running_on_dart/src/util/custom_task.dart';
import 'package:running_on_dart/src/util/jellyfin.dart';
import 'package:running_on_dart/src/util/pipelines.dart';
import 'package:tentacle/tentacle.dart';

final taskProgressFormat = NumberFormat("0.00");
Expand Down Expand Up @@ -47,25 +47,26 @@ final jellyfin = ChatGroup(
return SelectMenuOptionBuilder(label: label, value: taskInfo.id!, description: description);
}, authorOnly: true);

client.startTask(selectMenuResult.id!);
Pipeline.fromUpdateContext(
messageSupplier: (messageBuilder) => context.interaction.updateOriginalResponse(messageBuilder),
tasks: [
Task(
runCallback: () => client.startTask(selectMenuResult.id!),
updateCallback: () async {
final scheduledTask = (await client.getScheduledTasks())
.firstWhereOrNull((taskInfo) => taskInfo.id == selectMenuResult.id);
if (scheduledTask == null || scheduledTask.state == TaskState.idle) {
return (true, null);
}

CustomTask(
targetMessageCallback: () => context.interaction.updateOriginalResponse(
MessageUpdateBuilder(content: "Running `${selectMenuResult.name!}`", components: [])),
updateCallback: (builder) async {
final scheduledTask =
(await client.getScheduledTasks()).firstWhereOrNull((taskInfo) => taskInfo.id == selectMenuResult.id);
if (scheduledTask == null || scheduledTask.state == TaskState.idle) {
builder.content = "Running `${selectMenuResult.name!}` - Done!";
return true;
}

builder.content =
"Running `${scheduledTask.name!}` - ${taskProgressFormat.format(scheduledTask.currentProgressPercentage!)}%";
return false;
},
return (
false,
"Running `${scheduledTask.name!}` - ${taskProgressFormat.format(scheduledTask.currentProgressPercentage!)}%"
);
}),
],
updateInterval: Duration(seconds: 2),
);
).execute();
}),
),
]),
Expand Down
11 changes: 9 additions & 2 deletions lib/src/modules/bot_start_duration.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
class BotStartDuration {
final DateTime startDate = DateTime.now();
import 'package:running_on_dart/src/util/util.dart';

class BotStartDuration implements RequiresInitialization {
late final DateTime startDate;

@override
Future<void> init() async {
startDate = DateTime.now();
}
}
6 changes: 4 additions & 2 deletions lib/src/modules/docs.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import 'dart:async';
import 'package:fuzzy/fuzzy.dart';
import 'package:running_on_dart/running_on_dart.dart';
import 'package:running_on_dart/src/models/docs.dart';
import 'package:running_on_dart/src/util/util.dart';

class DocsModule {
class DocsModule implements RequiresInitialization {
final Map<String, PackageDocs> _cache = {};
DateTime? lastUpdate;

DocsModule() {
@override
Future<void> init() async {
for (final package in docsPackages) {
_cache[package] = PackageDocs(packageName: package);
}
Expand Down
13 changes: 8 additions & 5 deletions lib/src/modules/jellyfin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'package:injector/injector.dart';
import 'package:nyxx/nyxx.dart';
import 'package:running_on_dart/src/models/jellyfin_config.dart';
import 'package:running_on_dart/src/repository/jellyfin_config.dart';
import 'package:running_on_dart/src/util/util.dart';
import 'package:tentacle/tentacle.dart';
import 'package:tentacle/src/auth/auth.dart' show AuthInterceptor;
import 'package:dio/dio.dart' show RequestInterceptorHandler, RequestOptions;
Expand Down Expand Up @@ -103,16 +104,18 @@ class JellyfinClientWrapper {
Uri getJellyfinItemUrl(String itemId) => Uri.parse("$basePath/#/details?id=$itemId");
}

class JellyfinModule {
class JellyfinModule implements RequiresInitialization {
final Map<String, JellyfinClientWrapper> _jellyfinClients = {};
final Map<String, List<String>> _allowedUserRegistrations = {};

final JellyfinConfigRepository _jellyfinConfigRepository = Injector.appInstance.get();

JellyfinModule() {
_jellyfinConfigRepository
.getDefaultConfigs()
.then((defaultConfigs) => defaultConfigs.forEach((config) => _createClientConfig(config)));
@override
Future<void> init() async {
final defaultConfigs = await _jellyfinConfigRepository.getDefaultConfigs();
for (final config in defaultConfigs) {
_createClientConfig(config);
}
}

Future<void> deleteJellyfinConfig(JellyfinConfig config) async {
Expand Down
6 changes: 4 additions & 2 deletions lib/src/modules/join_logs.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@ import 'package:running_on_dart/src/models/feature_settings.dart';
import 'package:running_on_dart/src/repository/feature_settings.dart';
import 'package:running_on_dart/src/services/feature_settings.dart';
import 'package:running_on_dart/src/settings.dart';
import 'package:running_on_dart/src/util/util.dart';

class JoinLogsModule {
class JoinLogsModule implements RequiresInitialization {
final NyxxGateway _client = Injector.appInstance.get();
final FeatureSettingsRepository _featureSettingsRepository = Injector.appInstance.get();
final FeatureSettingsService _featureSettingsService = Injector.appInstance.get();

final Logger _logger = Logger('ROD.JoinLogs');

JoinLogsModule() {
@override
Future<void> init() async {
_client.onGuildMemberAdd.listen(_handle);
}

Expand Down
6 changes: 4 additions & 2 deletions lib/src/modules/mod_log.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import 'package:running_on_dart/running_on_dart.dart';
import 'package:running_on_dart/src/models/feature_settings.dart';
import 'package:running_on_dart/src/repository/feature_settings.dart';
import 'package:running_on_dart/src/services/feature_settings.dart';
import 'package:running_on_dart/src/util/util.dart';

class ModLogsModule {
class ModLogsModule implements RequiresInitialization {
final NyxxGateway _client = Injector.appInstance.get();
final FeatureSettingsRepository _featureSettingsRepository = Injector.appInstance.get();
final FeatureSettingsService _featureSettingsService = Injector.appInstance.get();
Expand All @@ -18,7 +19,8 @@ class ModLogsModule {
AuditLogEvent.memberKick,
];

ModLogsModule() {
@override
Future<void> init() async {
_client.onGuildAuditLogCreate.listen(_handleAuditLogAdd);
}

Expand Down
6 changes: 4 additions & 2 deletions lib/src/modules/poop_name.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ import 'package:nyxx/nyxx.dart';
import 'package:running_on_dart/src/models/feature_settings.dart';
import 'package:running_on_dart/src/services/feature_settings.dart';
import 'package:running_on_dart/src/settings.dart';
import 'package:running_on_dart/src/util/util.dart';

const poopEmoji = "💩";
final poopCharacters = ['!', '#', '@', '^', '%', '&', '-', '*', '.' '+', '\''];
final poopRegexp = RegExp("[${poopCharacters.join()}]");

class PoopNameModule {
class PoopNameModule implements RequiresInitialization {
final NyxxGateway _client = Injector.appInstance.get();

PoopNameModule() {
@override
Future<void> init() async {
_client.onGuildMemberAdd.listen((event) => _handle(event.member));
_client.onGuildMemberUpdate.listen((event) => _handle(event.member));
}
Expand Down
11 changes: 6 additions & 5 deletions lib/src/modules/reminder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:nyxx/nyxx.dart';
import 'package:nyxx_extensions/nyxx_extensions.dart';
import 'package:running_on_dart/src/models/reminder.dart';
import 'package:running_on_dart/src/repository/reminder.dart';
import 'package:running_on_dart/src/util/util.dart';

class ReminderModuleComponentId {
static String identifier = 'ReminderModuleComponentId';
Expand Down Expand Up @@ -33,17 +34,17 @@ class ReminderModuleComponentId {
String toString() => "$identifier/$reminderId/$userId/${duration.inMinutes}";
}

class ReminderModule {
class ReminderModule implements RequiresInitialization {
final List<Reminder> reminders = [];

final Logger _logger = Logger('ROD.ReminderModule');
final NyxxGateway _client = Injector.appInstance.get();
final ReminderRepository _reminderRepository = Injector.appInstance.get();

ReminderModule() {
_reminderRepository.fetchReminders().then((reminders) => this.reminders.addAll(reminders));

_processCurrent();
@override
Future<void> init() async {
reminders.addAll(await _reminderRepository.fetchReminders());
await _processCurrent();

_client.onMessageComponentInteraction
.where((event) => event.interaction.data.type == MessageComponentType.button)
Expand Down
6 changes: 4 additions & 2 deletions lib/src/modules/tag.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import 'package:nyxx/nyxx.dart';
import 'package:running_on_dart/src/models/tag.dart';
import 'package:running_on_dart/src/repository/tag.dart';
import 'package:running_on_dart/src/settings.dart';
import 'package:running_on_dart/src/util/util.dart';

class TagModule {
class TagModule implements RequiresInitialization {
final List<Tag> tags = [];
final List<TagUsedEvent> usedEvents = [];

final _tagRepository = Injector.appInstance.get<TagRepository>();

TagModule() {
@override
Future<void> init() async {
_tagRepository.fetchAllActiveTags().then((tags) => this.tags.addAll(tags));
_tagRepository.fetchTagUsage().then((events) => usedEvents.addAll(events));
}
Expand Down
17 changes: 5 additions & 12 deletions lib/src/services/db.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:migent/migent.dart';
import 'package:postgres/postgres.dart';

import 'package:running_on_dart/src/settings.dart';
import 'package:running_on_dart/src/util/util.dart';

/// The user to use when connecting to the database.
String user = getEnv('POSTGRES_USER');
Expand All @@ -23,17 +24,13 @@ String host = getEnv('DB_HOST', 'db');
/// The port to connect to the database on.
int port = int.parse(getEnv('DB_PORT', '5432'));

class DatabaseService {
/// The connection to the database.
class DatabaseService implements RequiresInitialization {
late PostgreSQLConnection _connection;

final Logger _logger = Logger('ROD.Database');

final Completer<void> _readyCompleter = Completer();
late final Future<void> _ready = _readyCompleter.future;

DatabaseService() {
_connect();
@override
Future<void> init() async {
await _connect();
}

/// Connect to the database and ensure the schema is up to date.
Expand Down Expand Up @@ -149,11 +146,7 @@ class DatabaseService {
await migrator.runMigrations();

_logger.info('Connected to database');

_readyCompleter.complete();
}

Future<void> awaitReady() async => await _ready;

PostgreSQLConnection getConnection() => _connection;
}
5 changes: 1 addition & 4 deletions lib/src/util/jellyfin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'package:intl/intl.dart';
import 'package:nyxx/nyxx.dart';
import 'package:nyxx_extensions/nyxx_extensions.dart';
import 'package:running_on_dart/src/modules/jellyfin.dart';
import 'package:running_on_dart/src/util/util.dart';
import 'package:tentacle/tentacle.dart';

final episodeSeriesNumberFormat = NumberFormat("00");
Expand All @@ -11,10 +12,6 @@ final itemCriticRatingNumberFormat = NumberFormat("00");

Duration parseDurationFromTicks(int ticks) => Duration(microseconds: ticks ~/ 10);

extension DurationFromTicks on Duration {
String formatShort() => toString().split('.').first.padLeft(8, "0");
}

String formatProgress(int currentPositionTicks, int totalTicks) {
final progressPercentage = currentPositionTicks / totalTicks * 100;

Expand Down
Loading

0 comments on commit 03d2044

Please sign in to comment.