Skip to content

Commit

Permalink
Add sessions page
Browse files Browse the repository at this point in the history
  • Loading branch information
l7ssha committed Nov 30, 2024
1 parent 517c45f commit 2b81d63
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 15 deletions.
4 changes: 3 additions & 1 deletion lib/src/init.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:injector/injector.dart';
import 'package:nyxx/nyxx.dart';
import 'package:running_on_dart/running_on_dart.dart';
import 'package:running_on_dart/src/modules/bot_start_duration.dart';
import 'package:running_on_dart/src/modules/docs.dart';
import 'package:running_on_dart/src/modules/emoji_react_module.dart';
Expand Down Expand Up @@ -55,7 +56,8 @@ Future<void> setupContainer(NyxxGateway client) async {
..registerSingleton(() => MentionsMonitoringModule())
..registerSingleton(() => KavitaModule())
..registerSingleton(() => EmojiReactModule())
..registerSingleton(() => BotInfoService());
..registerSingleton(() => BotInfoService())
..registerDependency<SessionManagerPlugin>(() => client.options.plugins.whereType<SessionManagerPlugin>().first);

await Injector.appInstance.get<DatabaseService>().init();
await Injector.appInstance.get<FeatureSettingsModule>().init();
Expand Down
23 changes: 20 additions & 3 deletions lib/src/web_app/api_server.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:injector/injector.dart';
import 'package:nyxx/nyxx.dart';
Expand All @@ -8,6 +9,7 @@ import 'package:running_on_dart/running_on_dart.dart';
import 'package:running_on_dart/src/modules/tag.dart';
import 'package:running_on_dart/src/repository/feature_settings.dart';
import 'package:running_on_dart/src/web_app/mustache.dart';
import 'package:running_on_dart/src/web_app/session_manager_plugin.dart';
import 'package:running_on_dart/src/web_app/utils.dart';
import 'package:running_on_dart/src/services/bot_info.dart';
import 'package:shelf_cors_headers/shelf_cors_headers.dart';
Expand All @@ -25,7 +27,19 @@ final clientSecret = getEnv('DISCORD_CLIENT_SECRET');
final clientRedirectUri = getEnv('DISCORD_REDIRECT_URI');

class WebServer {
final Logger _logger = Logger('WebServer');
final Logger _logger = Logger('ROD.WebServer');

Future<shelf.Response> _handleSessions(shelf.Request request) async {
if (!isAdminFromSession(request)) {
return shelf.Response.forbidden(null);
}

final sessions = jsonDecode(await File(sessionsFile).readAsString()) as Map<String, dynamic>;

return MustacheResponse(name: "sessions.html", parameters: {
'sessions': sessions.values.toList(),
});
}

Future<shelf.Response> _handleGuilds(shelf.Request request) async {
if (!isAdminFromSession(request)) {
Expand All @@ -43,7 +57,9 @@ class WebServer {
.fold(0, (previous, channel) => previous + channel.messages.cache.length);

final enabledFeatures =
await Injector.appInstance.get<FeatureSettingsRepository>().fetchSettingsForGuild(entry.id);
(await Injector.appInstance.get<FeatureSettingsRepository>().fetchSettingsForGuild(entry.id))
.map((s) => s.setting.name)
.join(", ");

final tagsCount = tagModule.getGuildTags(entry.id).length;

Expand All @@ -56,7 +72,7 @@ class WebServer {
'cached_channels': guildChannels.length,
'cached_messages': guildCachedMessages,
'cached_roles': entry.roles.cache.length,
'enabled_features': enabledFeatures.map((s) => s.setting.name).join(", "),
'enabled_features': enabledFeatures.isNotEmpty ? enabledFeatures : "None enabled",
'tags_count': tagsCount,
};
});
Expand Down Expand Up @@ -110,6 +126,7 @@ class WebServer {
Future<shelf_router.Router> _setupRouter() async {
return shelf_router.Router()
..get("/", _sessionAware(_processMustache(_handleIndex)))
..get('/sessions', _sessionAware(_processMustache(_handleSessions)))
..get("/guilds", _sessionAware(_processMustache(_handleGuilds)))
..get("/redirect", _sessionAware(_handleRedirect))
..get("/logout", _sessionAware(_handleLogOut));
Expand Down
16 changes: 8 additions & 8 deletions lib/src/web_app/session_manager_plugin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,34 @@ import 'dart:io';
import 'package:nyxx/nyxx.dart';
import 'package:shelf_session/session_middleware.dart';

class SessionManagerPlugin extends NyxxPlugin<NyxxGateway> {
static const _sessionsFile = '/sessions/sessions.json';
const sessionsFile = '/sessions/sessions.json';

void _saveSessions() async {
class SessionManagerPlugin extends NyxxPlugin<NyxxGateway> {
Future<void> triggerSaveSessions() async {
await saveSessions((sessionData) async {
logger.info("Saving session file");
await File(_sessionsFile).writeAsString(sessionData);
await File(sessionsFile).writeAsString(sessionData);
});
}

@override
FutureOr<void> afterConnect(NyxxGateway client) async {
await restoreSessions(() async {
final file = File(_sessionsFile);
final file = File(sessionsFile);
if (await file.exists()) {
logger.info("Loading session file.");
return File(_sessionsFile).readAsString();
return File(sessionsFile).readAsString();
}

logger.info("Session file missing. Returning default");
return '{}';
});

Timer.periodic(Duration(minutes: 15), (timer) => _saveSessions());
Timer.periodic(Duration(minutes: 15), (timer) => triggerSaveSessions());
}

@override
FutureOr<void> afterClose() async {
_saveSessions();
triggerSaveSessions();
}
}
3 changes: 3 additions & 0 deletions lib/src/web_app/utils.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'dart:convert';

import 'package:injector/injector.dart';
import 'package:nyxx/nyxx.dart';
import 'package:running_on_dart/running_on_dart.dart';
import 'package:shelf/shelf.dart' as shelf;
Expand Down Expand Up @@ -33,6 +34,8 @@ void initSession(shelf.Request request, Map<String, dynamic> userDataJson) {
session.data['is_admin'] = adminIds.contains(Snowflake.parse(userId));

session.expires = DateTime.now().add(Duration(days: 3));

Injector.appInstance.get<SessionManagerPlugin>().triggerSaveSessions();
}

void deleteSession(shelf.Request request) {
Expand Down
5 changes: 2 additions & 3 deletions templates/component/navigation.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@
<a class="nav-link active" aria-current="page" href="/">Home</a>
</li>
{{#is_admin}}
<li class="nav-item">
<a class="nav-link" href="/guilds">Guilds</a>
</li>
<li class="nav-item"> <a class="nav-link" href="/guilds">Guilds</a> </li>
<li class="nav-item"> <a class="nav-link" href="/sessions">Sessions</a> </li>
{{/is_admin}}
</ul>
<ul class="navbar-nav ms-auto mb-2 mb-lg-0 profile-menu">
Expand Down
32 changes: 32 additions & 0 deletions templates/sessions.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Running on Dart</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</head>
<body>
{{> navigation }}

<div class="container">
{{> alert }}

<div class="container">
<div class="accordion" id="guildsAccordion">
{{#sessions}}
{{#user_data}}
<div class="card">
<div class="card-body">
<img src="https://media.discordapp.net/avatars/{{id}}/{{avatar}}.png?size=32" alt="Profile Picture" class="rounded-circle">
<span class="ms-1 me-1 fw-bold"> {{name}} </span>
<span>Until: {{expires_t}}</span>
</div>
</div>
{{/user_data}}
{{/sessions}}
</div>
</div>
</div>
</body>
</html>

0 comments on commit 2b81d63

Please sign in to comment.