Compare commits

...
22 Commits
Author SHA1 Message Date
Mikescher b36c2215c0 [AUTO] Adjust gitea workflow for private goext dependency
Build Docker and Deploy / Build Docker Container (push) Successful in 3m33s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 6m43s
Build Docker and Deploy / Deploy to Server (push) Successful in 7s
2026-08-09 13:30:12 +02:00
Mikescher 61db95c94d [Web] Add app link
Build Docker and Deploy / Build Docker Container (push) Successful in 2m7s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 7m41s
Build Docker and Deploy / Deploy to Server (push) Successful in 21s
2026-07-22 14:06:57 +02:00
Mikescher 1074749cd0 [WebApp] AccountSwitcher 2026-07-22 13:56:09 +02:00
Mikescher 3759d3f6c6 [WebApp] Show username 2026-07-22 13:43:42 +02:00
Mikescher 1ecc5d7ebd [Server] Fix FTS search
Build Docker and Deploy / Build Docker Container (push) Successful in 2m35s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 4m54s
Build Docker and Deploy / Deploy to Server (push) Successful in 18s
2026-07-09 18:19:40 +02:00
Mikescher 0282bc0f0a show message timestamp in local tz
Build Docker and Deploy / Build Docker Container (push) Successful in 2m18s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 7m46s
Build Docker and Deploy / Deploy to Server (push) Successful in 14s
2026-06-26 09:20:07 +02:00
Mikescher bff8257f34 More flutter upgrades
Build Docker and Deploy / Build Docker Container (push) Successful in 1m4s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 7m40s
Build Docker and Deploy / Deploy to Server (push) Successful in 7s
2026-05-31 04:49:17 +02:00
Mikescher bb34f3b2b4 Flutter Fixes etc
Build Docker and Deploy / Build Docker Container (push) Successful in 1m7s
Build Docker and Deploy / Run Unit-Tests (push) Failing after 7m34s
Build Docker and Deploy / Deploy to Server (push) Has been skipped
2026-05-31 04:13:13 +02:00
Mikescher 0b7be0908d Upgrade flutter deps 2026-05-31 03:31:02 +02:00
Mikescher 55dc937385 Fix missing links in channel-list
Build Docker and Deploy / Build Docker Container (push) Successful in 2m2s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 7m42s
Build Docker and Deploy / Deploy to Server (push) Successful in 21s
2026-04-08 13:31:23 +02:00
Mikescher e98a804efc Fix panic in /preview/channel/{id}
Build Docker and Deploy / Build Docker Container (push) Successful in 1m49s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 7m56s
Build Docker and Deploy / Deploy to Server (push) Successful in 39s
2026-03-27 12:57:19 +01:00
Mikescher 1f9abb8574 WebApp: Fix channel-detail page for non-owned channels
Build Docker and Deploy / Build Docker Container (push) Successful in 1m48s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 4m11s
Build Docker and Deploy / Deploy to Server (push) Successful in 22s
2026-03-26 17:05:51 +01:00
Mikescher 9352ff5c2c UI improvements
Build Docker and Deploy / Build Docker Container (push) Successful in 51s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 7m29s
Build Docker and Deploy / Deploy to Server (push) Successful in 7s
2026-01-19 19:19:43 +01:00
Mikescher 1dafab8f5c skip some tests [skip-tests]
Build Docker and Deploy / Run Unit-Tests (push) Has been skipped
Build Docker and Deploy / Build Docker Container (push) Successful in 50s
Build Docker and Deploy / Deploy to Server (push) Successful in 24s
2026-01-19 19:07:35 +01:00
Mikescher b5e098a694 Show more data in webapp deliveries-table
Build Docker and Deploy / Build Docker Container (push) Successful in 1m25s
Build Docker and Deploy / Run Unit-Tests (push) Failing after 10m51s
Build Docker and Deploy / Deploy to Server (push) Has been skipped
2026-01-19 18:49:38 +01:00
Mikescher 08fd34632a Fix tests 2026-01-19 18:30:34 +01:00
Mikescher a7a2474e2a Increase quota
Build Docker and Deploy / Build Docker Container (push) Successful in 1m3s
Build Docker and Deploy / Run Unit-Tests (push) Failing after 8m51s
Build Docker and Deploy / Deploy to Server (push) Has been skipped
2025-12-18 15:41:17 +01:00
Mikescher e15d70dd0e [Flutter] Force a username before subscribing 2025-12-18 15:30:58 +01:00
Mikescher e98882a0c6 Skip [TestRequestLogAPI] test
Build Docker and Deploy / Build Docker Container (push) Successful in 54s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 9m2s
Build Docker and Deploy / Deploy to Server (push) Successful in 18s
2025-12-18 15:25:15 +01:00
Mikescher 24bf7cd434 Fix notification sounds under iOS
Build Docker and Deploy / Build Docker Container (push) Successful in 1m38s
Build Docker and Deploy / Run Unit-Tests (push) Failing after 9m23s
Build Docker and Deploy / Deploy to Server (push) Has been skipped
2025-12-18 15:02:51 +01:00
Mikescher 54c4f873fc [Flutter] Use deviceName instead of hostName for clients 2025-12-18 14:57:46 +01:00
Mikescher b2de793758 [Flutter] Fix sending notifications without content 2025-12-18 14:36:45 +01:00
77 changed files with 15163 additions and 14276 deletions
+9 -5
View File
@@ -3,7 +3,9 @@ plugins {
// START: FlutterFire Configuration
id 'com.google.gms.google-services'
// END: FlutterFire Configuration
id "kotlin-android"
// Kotlin is provided by Flutter's built-in Kotlin support (the flutter-gradle-plugin
// auto-applies kotlin-android). KGP stays declared in settings.gradle so it remains
// on the classpath. See https://docs.flutter.dev/release/breaking-changes/migrate-to-built-in-kotlin/for-app-developers
id "dev.flutter.flutter-gradle-plugin"
}
@@ -42,10 +44,6 @@ android {
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = '17'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
@@ -75,6 +73,12 @@ android {
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
flutter {
source '../..'
}
+4
View File
@@ -1,3 +1,7 @@
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
# This builtInKotlin flag was added automatically by Flutter migrator
android.builtInKotlin=false
# This newDsl flag was added automatically by Flutter migrator
android.newDsl=false
File diff suppressed because it is too large Load Diff
@@ -1,85 +1,12 @@
library font_awesome_flutter;
import 'package:flutter/widgets.dart';
/// [IconData] for a font awesome brand icon from a code point
///
/// Code points can be obtained from fontawesome.com
class IconDataBrands extends IconData {
const IconDataBrands(int codePoint)
: super(
codePoint,
fontFamily: 'FontAwesomeBrands',
fontPackage: 'font_awesome_flutter',
);
}
/// [IconData] for a font awesome solid icon from a code point
///
/// Code points can be obtained from fontawesome.com
class IconDataSolid extends IconData {
const IconDataSolid(int codePoint)
: super(
codePoint,
fontFamily: 'FontAwesomeSolid',
fontPackage: 'font_awesome_flutter',
);
}
/// [IconData] for a font awesome regular icon from a code point
///
/// Code points can be obtained from fontawesome.com
class IconDataRegular extends IconData {
const IconDataRegular(int codePoint)
: super(
codePoint,
fontFamily: 'FontAwesomeRegular',
fontPackage: 'font_awesome_flutter',
);
}
/// [IconData] for a font awesome light icon from a code point. Only works if
/// light icons (font awesome pro) have been installed.
///
/// Code points can be obtained from fontawesome.com
class IconDataLight extends IconData {
const IconDataLight(int codePoint)
: super(
codePoint,
fontFamily: 'FontAwesomeLight',
fontPackage: 'font_awesome_flutter',
);
}
/// [IconData] for a font awesome duotone icon from a code point. Only works if
/// duotone icons (font awesome pro) have been installed.
///
/// Code points can be obtained from fontawesome.com. Each duotone icon consists
/// of a primary [codePoint] and a [secondary].
class IconDataDuotone extends IconData {
/// Secondary glyph of the duotone icon
///
/// Due to tree-shaking restraints [secondary] cannot be the codepoint itself,
/// but has to be an [IconData] object.
final IconData? secondary;
const IconDataDuotone(int codePoint, {this.secondary})
: super(
codePoint,
fontFamily: 'FontAwesomeDuotone',
fontPackage: 'font_awesome_flutter',
);
}
/// [IconData] for a font awesome thin icon from a code point. Only works if
/// thin icons (font awesome pro, v6+) have been installed.
///
/// Code points can be obtained from fontawesome.com
class IconDataThin extends IconData {
const IconDataThin(int codePoint)
: super(
codePoint,
fontFamily: 'FontAwesomeThin',
fontPackage: 'font_awesome_flutter',
);
}
// NOTE:
// This file previously declared IconDataBrands / IconDataSolid / IconDataRegular
// / IconDataLight / IconDataThin / IconDataDuotone as subclasses of [IconData].
// Newer Flutter SDKs mark [IconData] as a `final class`, which can no longer be
// extended outside its own library, so those subclasses no longer compile.
//
// The generated icon constants in `font_awesome_flutter.dart` now construct
// plain `const IconData(..., fontFamily: '<FontAwesome...>', fontPackage:
// 'font_awesome_flutter')` directly, so these helper subclasses are no longer
// needed. Using const [IconData] literals also keeps icon tree-shaking working.
+3 -3
View File
@@ -205,7 +205,7 @@ class APIClient {
fn: User.fromJson,
authToken: auth.getToken(),
query: {
'confirm': ['true']
'confirm': ['true'],
},
);
}
@@ -230,7 +230,7 @@ class APIClient {
static Future<Client> updateClient(TokenSource auth, String clientID, {String? fcmToken, String? agentModel, String? name, String? agentVersion}) async {
return await _request(
name: 'updateClient',
method: 'PUT',
method: 'PATCH',
relURL: 'users/${auth.getUserID()}/clients/$clientID',
jsonBody: {
if (fcmToken != null) 'fcm_token': fcmToken,
@@ -259,7 +259,7 @@ class APIClient {
method: 'GET',
relURL: 'users/${auth.getUserID()}/channels',
query: {
'selector': [sel.apiKey]
'selector': [sel.apiKey],
},
fn: (json) => ChannelWithSubscription.fromJsonArray(json['channels'] as List<dynamic>),
authToken: auth.getToken(),
@@ -98,7 +98,7 @@ class _SCNNavLayoutState extends State<SCNNavLayout> {
selectedIndex: _selectedIndex,
onTabSelected: _onItemTapped,
color: Theme.of(context).disabledColor,
selectedColor: Theme.of(context).primaryColorDark,
selectedColor: Theme.of(context).colorScheme.primary,
notchedShape: const AutomaticNotchedShape(
RoundedRectangleBorder(
borderRadius: BorderRadius.only(
+1 -1
View File
@@ -31,7 +31,7 @@ class SCNScaffold extends StatelessWidget {
showShare: showShare,
onShare: onShare ?? () {},
),
body: child,
body: SafeArea(child: child),
floatingActionButton: floatingActionButton,
);
}
+31 -10
View File
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:provider/provider.dart';
import 'package:simplecloudnotifier/api/api_client.dart';
import 'package:simplecloudnotifier/main_messaging.dart';
import 'package:simplecloudnotifier/main_utils.dart';
import 'package:simplecloudnotifier/components/layout/nav_layout.dart';
@@ -68,15 +69,17 @@ void main() async {
print('[INIT] Request Notification permissions...');
await FirebaseMessaging.instance.requestPermission(provisional: true);
FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) {
try {
setFirebaseToken(fcmToken);
} catch (exc, trace) {
ApplicationLog.error('Failed to set firebase token: ' + exc.toString(), trace: trace);
}
}).onError((dynamic err) {
ApplicationLog.error('Failed to listen to token refresh events: ' + (err?.toString() ?? ''));
});
FirebaseMessaging.instance.onTokenRefresh
.listen((fcmToken) {
try {
setFirebaseToken(fcmToken);
} catch (exc, trace) {
ApplicationLog.error('Failed to set firebase token: ' + exc.toString(), trace: trace);
}
})
.onError((dynamic err) {
ApplicationLog.error('Failed to listen to token refresh events: ' + (err?.toString() ?? ''));
});
try {
print('[INIT] Query firebase token...');
@@ -96,6 +99,25 @@ void main() async {
await appAuth.tryMigrateFromV1();
if (appAuth.isAuth()) {
print('[INIT] Load Client and potentially update...');
try {
var client = await appAuth.loadClient(onlyCached: true);
if (client != null) {
if (client.agentModel != Globals().deviceModel || client.name != Globals().nameForClient() || client.agentVersion != Globals().version) {
print('[INIT] Update Client info...');
final newClient = await APIClient.updateClient(appAuth, client.clientID, agentModel: Globals().deviceModel, name: Globals().nameForClient(), agentVersion: Globals().version);
appAuth.setClientAndClientID(newClient);
await appAuth.save();
}
}
} catch (exc, trace) {
ApplicationLog.error('Failed to get client (on init): ' + exc.toString(), trace: trace);
}
}
print('[INIT] Load Notifications...');
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
@@ -110,7 +132,6 @@ void main() async {
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification: receiveLocalDarwinNotification,
notificationCategories: getDarwinNotificationCategories(),
);
final initializationSettingsLinux = LinuxInitializationSettings(defaultActionName: 'Open notification');
-5
View File
@@ -107,11 +107,6 @@ Future<void> _receiveMessage(RemoteMessage message, bool foreground) async {
}
}
void receiveLocalDarwinNotification(int id, String? title, String? body, String? payload) {
//TODO iOS?
ApplicationLog.info('Received local notification<darwin>: $id -> [$title]');
}
void receiveLocalNotification(NotificationResponse details) {
// User has tapped a flutter_local notification, while the app was running
ApplicationLog.info('Tapped local notification: [[${details.id} | ${details.actionId} | ${details.input} | ${details.notificationResponseType} | ${details.payload}]]');
+2 -2
View File
@@ -40,11 +40,11 @@ void setFirebaseToken(String fcmToken) async {
if (client == null) {
// should not really happen - perhaps someone externally deleted the client?
final newClient = await APIClient.addClient(acc, fcmToken, Globals().deviceModel, Globals().version, Globals().hostname, Globals().clientType);
final newClient = await APIClient.addClient(acc, fcmToken, Globals().deviceModel, Globals().version, Globals().nameForClient(), Globals().clientType);
acc.setClientAndClientID(newClient);
await acc.save();
} else {
final newClient = await APIClient.updateClient(acc, client.clientID, fcmToken: fcmToken, agentModel: Globals().deviceModel, name: Globals().hostname, agentVersion: Globals().version);
final newClient = await APIClient.updateClient(acc, client.clientID, fcmToken: fcmToken, agentModel: Globals().deviceModel, name: Globals().nameForClient(), agentVersion: Globals().version);
acc.setClientAndClientID(newClient);
await acc.save();
}
+1 -1
View File
@@ -527,7 +527,7 @@ class _AccountRootPageState extends State<AccountRootPage> {
await Globals().setPrefFCMToken(fcmToken);
final user = await APIClient.createUserWithClient(null, fcmToken, Globals().platform, Globals().version, Globals().hostname, Globals().clientType);
final user = await APIClient.createUserWithClient(null, fcmToken, Globals().platform, Globals().version, Globals().nameForClient(), Globals().clientType);
acc.set(user.user, user.clients[0], user.adminKey, user.sendKey);
+1 -1
View File
@@ -156,7 +156,7 @@ class _AccountLoginPageState extends State<AccountLoginPage> {
final user = await APIClient.getUser(DirectTokenSource(uid, atokv), uid);
final client = await APIClient.addClient(DirectTokenSource(uid, atokv), fcmToken, Globals().deviceModel, Globals().version, Globals().hostname, Globals().clientType);
final client = await APIClient.addClient(DirectTokenSource(uid, atokv), fcmToken, Globals().deviceModel, Globals().version, Globals().nameForClient(), Globals().clientType);
acc.set(user, client, atokv, stokv);
await acc.save();
@@ -69,65 +69,74 @@ class _ChannelListItemState extends State<ChannelListItem> {
margin: EdgeInsets.fromLTRB(0, 4, 0, 4),
shape: BeveledRectangleBorder(borderRadius: BorderRadius.circular(0)),
color: Theme.of(context).cardTheme.color,
child: InkWell(
onTap: () {
if (widget.mode == ChannelListItemMode.Messages) {
Navi.push(context, () => ChannelMessageViewPage(channel: widget.channel));
} else {
Navi.push(context, () => ChannelViewPage(channelID: widget.channel.channelID, preloadedData: (widget.channel, widget.subscription), needsReload: widget.onChannelListReloadTrigger));
}
},
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
_buildIcon(context),
SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
widget.channel.displayName,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
Text(
(widget.channel.timestampLastSent == null) ? '' : dateFormat.format(DateTime.parse(widget.channel.timestampLastSent!).toLocal()),
style: const TextStyle(fontSize: 14),
),
],
),
SizedBox(height: 4),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(child: (widget.mode == ChannelListItemMode.Messages) ? Text(_preformatTitle(lastMessage), style: TextStyle(color: Theme.of(context).textTheme.bodyLarge?.color?.withAlpha(160))) : _buildSubscriptionStateText(context)),
(widget.mode == ChannelListItemMode.Messages) ? Text(widget.channel.messagesSent.toString(), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)) : Text("", style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
],
),
],
),
),
SizedBox(width: 4),
GestureDetector(
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: InkWell(
onTap: () {
if (widget.mode == ChannelListItemMode.Messages) {
Navi.push(context, () => ChannelViewPage(channelID: widget.channel.channelID, preloadedData: (widget.channel, widget.subscription), needsReload: widget.onChannelListReloadTrigger));
} else {
Navi.push(context, () => ChannelMessageViewPage(channel: widget.channel));
} else {
Navi.push(context, () => ChannelViewPage(channelID: widget.channel.channelID, preloadedData: (widget.channel, widget.subscription), needsReload: widget.onChannelListReloadTrigger));
}
},
child: Padding(
padding: const EdgeInsets.all(8),
child: (widget.mode == ChannelListItemMode.Messages) ? Icon(FontAwesomeIcons.solidSquareInfo, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(128), size: 24) : Icon(FontAwesomeIcons.solidEnvelopes, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(128), size: 24),
child: Row(
children: [
_buildIcon(context),
SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
widget.channel.displayName,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
Text(
(widget.channel.timestampLastSent == null) ? '' : dateFormat.format(DateTime.parse(widget.channel.timestampLastSent!).toLocal()),
style: const TextStyle(fontSize: 14),
),
],
),
SizedBox(height: 4),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(child: (widget.mode == ChannelListItemMode.Messages) ? Text(_preformatTitle(lastMessage), style: TextStyle(color: Theme.of(context).textTheme.bodyLarge?.color?.withAlpha(160))) : _buildSubscriptionStateText(context)),
(widget.mode == ChannelListItemMode.Messages) ? Text(widget.channel.messagesSent.toString(), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)) : Text("", style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
],
),
],
),
),
],
),
),
),
],
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
if (widget.mode == ChannelListItemMode.Messages) {
Navi.push(context, () => ChannelViewPage(channelID: widget.channel.channelID, preloadedData: (widget.channel, widget.subscription), needsReload: widget.onChannelListReloadTrigger));
} else {
Navi.push(context, () => ChannelMessageViewPage(channel: widget.channel));
}
},
child: Padding(
padding: const EdgeInsets.only(left: 12, right: 16),
child: Center(widthFactor: 1.0, child: (widget.mode == ChannelListItemMode.Messages) ? Icon(FontAwesomeIcons.solidSquareInfo, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(128), size: 24) : Icon(FontAwesomeIcons.solidEnvelopes, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(128), size: 24)),
),
),
],
),
),
);
@@ -12,6 +12,7 @@ import 'package:simplecloudnotifier/state/app_auth.dart';
import 'package:simplecloudnotifier/state/application_log.dart';
import 'package:simplecloudnotifier/utils/navi.dart';
import 'package:simplecloudnotifier/utils/toaster.dart';
import 'package:simplecloudnotifier/utils/dialogs.dart';
import 'package:simplecloudnotifier/utils/ui.dart';
class ChannelScannerResultChannelSubscribe extends StatefulWidget {
@@ -172,6 +173,38 @@ class _ChannelScannerResultChannelSubscribeState extends State<ChannelScannerRes
void _onSubscribe() async {
final auth = Provider.of<AppAuth>(context, listen: false);
// Check if username is set
try {
final user = await auth.loadUser();
if (user.username == null || user.username!.isEmpty) {
// Show modal to set username
var newusername = await UIDialogs.showUsernameRequiredDialog(context);
if (newusername == null) return; // User cancelled
newusername = newusername.trim();
if (newusername.isEmpty) {
Toaster.error("Error", 'Username cannot be empty');
return;
}
// Update username via API
try {
await APIClient.updateUser(auth, auth.userID!, username: newusername);
await auth.loadUser(force: true); // Refresh cached user
Toaster.success("Success", 'Username set');
} catch (e) {
Toaster.error("Error", 'Failed to set username: ${e.toString()}');
return;
}
}
} catch (e) {
Toaster.error("Error", 'Failed to load user data: ${e.toString()}');
return;
}
// Proceed with subscription
try {
var sub = await APIClient.subscribeToChannelbyID(auth, widget.value.channelID, subscribeKey: widget.value.subscribeKey);
if (sub.confirmed) {
@@ -5,6 +5,7 @@ import 'package:simplecloudnotifier/api/api_client.dart';
import 'package:simplecloudnotifier/state/app_settings.dart';
import 'package:simplecloudnotifier/state/app_auth.dart';
import 'package:simplecloudnotifier/state/application_log.dart';
import 'package:simplecloudnotifier/state/globals.dart';
import 'package:simplecloudnotifier/utils/notifier.dart';
import 'package:simplecloudnotifier/utils/toaster.dart';
import 'package:simplecloudnotifier/utils/ui.dart';
@@ -65,22 +66,31 @@ class _DebugActionsPageState extends State<DebugActionsPage> {
onPressed: _sendTokenToServer,
text: 'Send FCM Token to Server',
),
SizedBox(height: 4),
UI.button(
big: false,
onPressed: _updateClient,
text: 'Update Client on Server',
),
SizedBox(height: 20),
UI.button(
big: false,
onPressed: () => Notifier.showLocalNotification('', 'TEST_CHANNEL', "Test Channel", "Channel for testing", "Hello World", "Local Notification test", null, null),
text: 'Show local notification (generic)',
),
SizedBox(height: 4),
UI.button(
big: false,
onPressed: () => Notifier.showLocalNotification('', 'TEST_CHANNEL', "Test Channel", "Channel for testing", "Hello World", "Local Notification test", null, 0),
text: 'Show local notification (Prio = 0)',
),
SizedBox(height: 4),
UI.button(
big: false,
onPressed: () => Notifier.showLocalNotification('', 'TEST_CHANNEL', "Test Channel", "Channel for testing", "Hello World", "Local Notification test", null, 1),
text: 'Show local notification (Prio = 1)',
),
SizedBox(height: 4),
UI.button(
big: false,
onPressed: () => Notifier.showLocalNotification('', 'TEST_CHANNEL', "Test Channel", "Channel for testing", "Hello World", "Local Notification test", null, 2),
@@ -128,6 +138,26 @@ class _DebugActionsPageState extends State<DebugActionsPage> {
}
}
void _updateClient() async {
try {
final auth = AppAuth();
final clientID = auth.getClientID();
if (clientID == null) {
Toaster.error("Error", "No Client set");
return;
}
final newClient = await APIClient.updateClient(auth, clientID, agentModel: Globals().deviceModel, name: Globals().nameForClient(), agentVersion: Globals().version);
auth.setClientAndClientID(newClient);
Toaster.success("Success", "Client updated");
} catch (exc, trace) {
Toaster.error("Error", "An error occurred while updating the client: ${exc.toString()}");
ApplicationLog.error("An error occurred while updating the client: ${exc.toString()}", trace: trace);
}
}
void _copyToken() async {
try {
final fcmToken = await FirebaseMessaging.instance.getToken();
@@ -135,7 +135,7 @@ class _DebugRequestViewPageState extends State<DebugRequestViewPage> {
void _copyCurl() {
final method = '-X ${widget.request.method}';
final header = widget.request.requestHeaders.entries.map((v) => '-H "${v.key}: ${v.value}"').join(' ');
final body = widget.request.requestBody.isNotEmpty ? '-d "${widget.request.requestBody}"' : '';
final body = widget.request.requestBody.isNotEmpty ? '-d \'${widget.request.requestBody}\'' : '';
final curlParts = ['curl', method, header, '"${widget.request.url}"', body];
@@ -31,62 +31,71 @@ class KeyTokenListItem extends StatelessWidget {
margin: EdgeInsets.fromLTRB(0, 4, 0, 4),
shape: BeveledRectangleBorder(borderRadius: BorderRadius.circular(0)),
color: Theme.of(context).cardTheme.color,
child: InkWell(
onTap: () {
Navi.push(context, () => KeyTokenViewPage(keytokenID: item.keytokenID, preloadedData: item, needsReload: needsReload));
},
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
Icon(FontAwesomeIcons.solidGearCode, color: Theme.of(context).colorScheme.outline, size: 32),
SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
item.name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
Text(
(item.timestampLastUsed == null) ? '' : dateFormat.format(DateTime.parse(item.timestampLastUsed!).toLocal()),
style: const TextStyle(fontSize: 14),
),
],
),
SizedBox(height: 4),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Text(
"Permissions: " + _formatPermissions(item.permissions, item.allChannels, item.channels),
style: TextStyle(color: Theme.of(context).textTheme.bodyLarge?.color?.withAlpha(160)),
),
),
Text(item.messagesSent.toString(), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
],
),
],
),
),
SizedBox(width: 4),
GestureDetector(
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: InkWell(
onTap: () {
Navi.push(context, () => FilteredMessageViewPage(title: item.name, alertText: 'All message sent with the key \'${item.name}\'', filter: MessageFilter(usedKeys: [item.keytokenID])));
Navi.push(context, () => KeyTokenViewPage(keytokenID: item.keytokenID, preloadedData: item, needsReload: needsReload));
},
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(FontAwesomeIcons.solidEnvelopes, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(128), size: 24),
child: Row(
children: [
Icon(FontAwesomeIcons.solidGearCode, color: Theme.of(context).colorScheme.outline, size: 32),
SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
item.name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
Text(
(item.timestampLastUsed == null) ? '' : dateFormat.format(DateTime.parse(item.timestampLastUsed!).toLocal()),
style: const TextStyle(fontSize: 14),
),
],
),
SizedBox(height: 4),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Text(
"Permissions: " + _formatPermissions(item.permissions, item.allChannels, item.channels),
style: TextStyle(color: Theme.of(context).textTheme.bodyLarge?.color?.withAlpha(160)),
),
),
Text(item.messagesSent.toString(), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
],
),
],
),
),
],
),
),
),
],
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navi.push(context, () => FilteredMessageViewPage(title: item.name, alertText: 'All message sent with the key \'${item.name}\'', filter: MessageFilter(usedKeys: [item.keytokenID])));
},
child: Padding(
padding: const EdgeInsets.only(left: 12, right: 16),
child: Center(widthFactor: 1.0, child: Icon(FontAwesomeIcons.solidEnvelopes, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(128), size: 24)),
),
),
],
),
),
);
@@ -140,6 +140,7 @@ class _MessageViewPageState extends State<MessageViewPage> {
Widget _buildMessageView(BuildContext context, SCNMessage message, ChannelPreview? channel, KeyTokenPreview? token, UserPreview? user) {
final userAccUserID = context.select<AppAuth, String?>((v) => v.userID);
final dateFormat = context.select<AppSettings, AppSettingsDateFormat>((v) => v.dateFormat).dateFormat();
var cfg = AppSettings();
@@ -229,7 +230,7 @@ class _MessageViewPageState extends State<MessageViewPage> {
}
: null,
),
UI.metaCard(context: context, icon: FontAwesomeIcons.solidTimer, title: 'Timestamp', values: [message.timestamp]),
UI.metaCard(context: context, icon: FontAwesomeIcons.solidTimer, title: 'Timestamp', values: [dateFormat.format(DateTime.parse(message.timestamp).toLocal())]),
if (cfg.showExtendedAttributes)
UI.metaCard(
context: context,
@@ -319,7 +320,7 @@ class _MessageViewPageState extends State<MessageViewPage> {
children: [
UI.channelChip(context: context, text: _resolveChannelName(channel, message), margin: const EdgeInsets.fromLTRB(0, 0, 4, 0), fontSize: 16),
Expanded(child: SizedBox()),
Text(dateFormat.format(DateTime.parse(message.timestamp)), style: const TextStyle(fontSize: 14)),
Text(dateFormat.format(DateTime.parse(message.timestamp).toLocal()), style: const TextStyle(fontSize: 14)),
],
),
SizedBox(height: 8),
+8 -2
View File
@@ -284,7 +284,9 @@ class _SendRootPageState extends State<SendRootPage> {
}
try {
await APIClient.sendMessage(acc.userID!, acc.tokenSend!, _msgContent.text);
var content = (_msgContent.text != '') ? _msgContent.text : null;
await APIClient.sendMessage(acc.userID!, acc.tokenSend!, _msgTitle.text, content: content);
Toaster.success("Success", 'Message sent');
setState(() {
_msgTitle.clear();
@@ -306,7 +308,11 @@ class _SendRootPageState extends State<SendRootPage> {
}
try {
await APIClient.sendMessage(acc.userID!, acc.tokenSend!, _msgContent.text, channel: _channelName.text, senderName: _senderName.text, priority: _priority);
var content = (_msgContent.text != '') ? _msgContent.text : null;
var channel = (_channelName.text != '') ? _channelName.text : null;
var sender = (_senderName.text != '') ? _senderName.text : null;
await APIClient.sendMessage(acc.userID!, acc.tokenSend!, _msgTitle.text, content: content, channel: channel, senderName: sender, priority: _priority);
Toaster.success("Success", 'Message sent');
setState(() {
_msgTitle.clear();
@@ -28,58 +28,67 @@ class SenderListItem extends StatelessWidget {
margin: EdgeInsets.fromLTRB(0, 4, 0, 4),
shape: BeveledRectangleBorder(borderRadius: BorderRadius.circular(0)),
color: Theme.of(context).cardTheme.color,
child: InkWell(
onTap: () {
Navi.push(context, () => FilteredMessageViewPage(title: item.name, alertText: 'All message sent from \'${item.name!}\'', filter: MessageFilter(senderNames: [item.name])));
},
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
Icon(FontAwesomeIcons.solidSignature, color: Theme.of(context).colorScheme.outline, size: 32),
SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
item.name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
SizedBox(height: 4),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Text(
dateFormat.format(DateTime.parse(item.lastTimestamp).toLocal()),
style: TextStyle(color: Theme.of(context).textTheme.bodyLarge?.color?.withAlpha(160)),
),
),
Text(item.count.toString(), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
],
),
],
),
),
SizedBox(width: 4),
GestureDetector(
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: InkWell(
onTap: () {
Navi.push(context, () => FilteredMessageViewPage(title: item.name, alertText: 'All message sent from \'${item.name!}\'', filter: MessageFilter(senderNames: [item.name])));
Navi.push(context, () => FilteredMessageViewPage(title: item.name, alertText: 'All message sent from \'${item.name}\'', filter: MessageFilter(senderNames: [item.name])));
},
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(FontAwesomeIcons.solidEnvelopes, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(128), size: 24),
child: Row(
children: [
Icon(FontAwesomeIcons.solidSignature, color: Theme.of(context).colorScheme.outline, size: 32),
SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
item.name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
SizedBox(height: 4),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Text(
dateFormat.format(DateTime.parse(item.lastTimestamp).toLocal()),
style: TextStyle(color: Theme.of(context).textTheme.bodyLarge?.color?.withAlpha(160)),
),
),
Text(item.count.toString(), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
],
),
],
),
),
],
),
),
),
],
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navi.push(context, () => FilteredMessageViewPage(title: item.name, alertText: 'All message sent from \'${item.name}\'', filter: MessageFilter(senderNames: [item.name])));
},
child: Padding(
padding: const EdgeInsets.only(left: 12, right: 16),
child: Center(widthFactor: 1.0, child: Icon(FontAwesomeIcons.solidEnvelopes, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(128), size: 24)),
),
),
],
),
),
);
+6 -2
View File
@@ -99,7 +99,7 @@ class AppAuth extends ChangeNotifier implements TokenSource {
final user = await APIClient.getUser(DirectTokenSource(oldUserID, oldUserKey), oldUserID);
final client = await APIClient.addClient(DirectTokenSource(oldUserID, oldUserKey), fcmToken, Globals().deviceModel, Globals().version, Globals().hostname, Globals().clientType);
final client = await APIClient.addClient(DirectTokenSource(oldUserID, oldUserKey), fcmToken, Globals().deviceModel, Globals().version, Globals().nameForClient(), Globals().clientType);
set(user, client, oldUserKey, newTokenSend.token);
@@ -232,7 +232,7 @@ class AppAuth extends ChangeNotifier implements TokenSource {
return _user?.$1;
}
Future<Client?> loadClient({bool force = false, Duration? forceIfOlder = null}) async {
Future<Client?> loadClient({bool force = false, Duration? forceIfOlder = null, bool onlyCached = false}) async {
if (forceIfOlder != null && _client != null && _client!.$2.difference(DateTime.now()) > forceIfOlder) {
force = true;
}
@@ -245,6 +245,10 @@ class AppAuth extends ChangeNotifier implements TokenSource {
throw Exception('Not authenticated');
}
if (onlyCached) {
return null;
}
try {
final client = await APIClient.getClient(this, _clientID!);
+8
View File
@@ -92,4 +92,12 @@ class Globals {
Future<bool> setPrefFCMToken(String value) {
return sharedPrefs.setString("fcm.token", value);
}
String nameForClient() {
if (this.deviceName.isNotEmpty) {
return this.deviceName;
} else {
return this.hostname;
}
}
}
+34
View File
@@ -28,6 +28,40 @@ class UIDialogs {
);
}
static Future<String?> showUsernameRequiredDialog(BuildContext context) {
var _textFieldController = TextEditingController();
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Username Required'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Please set a public username to subscribe to channels from other users.'),
SizedBox(height: 16),
TextField(
autofocus: true,
controller: _textFieldController,
decoration: InputDecoration(hintText: 'Enter username'),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(_textFieldController.text),
child: Text('OK'),
),
],
),
);
}
static Future<bool> showConfirmDialog(BuildContext context, String title, {String? text, String? okText, String? cancelText}) {
return showDialog<bool>(
context: context,
+72 -72
View File
@@ -149,10 +149,10 @@ packages:
dependency: transitive
description:
name: characters
sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.4.1"
checked_yaml:
dependency: transitive
description:
@@ -205,10 +205,10 @@ packages:
dependency: transitive
description:
name: cross_file
sha256: "942a4791cd385a68ccb3b32c71c427aba508a1bb949b86dff2adbe4049f16239"
sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937"
url: "https://pub.dev"
source: hosted
version: "0.3.5"
version: "0.3.5+2"
crypto:
dependency: transitive
description:
@@ -221,10 +221,10 @@ packages:
dependency: "direct main"
description:
name: cupertino_icons
sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"
url: "https://pub.dev"
source: hosted
version: "1.0.8"
version: "1.0.9"
dart_style:
dependency: transitive
description:
@@ -245,18 +245,18 @@ packages:
dependency: "direct main"
description:
name: device_info_plus
sha256: "98f28b42168cc509abc92f88518882fd58061ea372d7999aecc424345c7bff6a"
sha256: "6a642e1daa10190af89ba6cb6386c0df7d071a3592080bfe1e44faa63ae1df65"
url: "https://pub.dev"
source: hosted
version: "11.5.0"
version: "13.1.0"
device_info_plus_platform_interface:
dependency: transitive
description:
name: device_info_plus_platform_interface
sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f
sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46"
url: "https://pub.dev"
source: hosted
version: "7.0.3"
version: "8.1.0"
encrypt:
dependency: transitive
description:
@@ -285,10 +285,18 @@ packages:
dependency: transitive
description:
name: ffi
sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418"
sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
version: "2.2.0"
ffi_leak_tracker:
dependency: transitive
description:
name: ffi_leak_tracker
sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
file:
dependency: transitive
description:
@@ -378,42 +386,42 @@ packages:
dependency: "direct main"
description:
name: flutter_lazy_indexed_stack
sha256: "3e905c0f130538f686e4e07bb8d0bc0dee6890366c65da199fb356aab52e0bff"
sha256: e5a6c061a336dcb6f6758d63c7d3d40698a4581e766da6de00ed2b8822b15199
url: "https://pub.dev"
source: hosted
version: "0.0.7"
version: "0.1.0"
flutter_lints:
dependency: "direct dev"
description:
name: flutter_lints
sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1"
sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1"
url: "https://pub.dev"
source: hosted
version: "5.0.0"
version: "6.0.0"
flutter_local_notifications:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: "674173fd3c9eda9d4c8528da2ce0ea69f161577495a9cc835a2a4ecd7eadeb35"
sha256: ef41ae901e7529e52934feba19ed82827b11baa67336829564aeab3129460610
url: "https://pub.dev"
source: hosted
version: "17.2.4"
version: "18.0.1"
flutter_local_notifications_linux:
dependency: transitive
description:
name: flutter_local_notifications_linux
sha256: c49bd06165cad9beeb79090b18cd1eb0296f4bf4b23b84426e37dd7c027fc3af
sha256: "8f685642876742c941b29c32030f6f4f6dacd0e4eaecb3efbb187d6a3812ca01"
url: "https://pub.dev"
source: hosted
version: "4.0.1"
version: "5.0.0"
flutter_local_notifications_platform_interface:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
sha256: "85f8d07fe708c1bdcf45037f2c0109753b26ae077e9d9e899d55971711a4ea66"
sha256: "6c5b83c86bf819cdb177a9247a3722067dd8cc6313827ce7c77a4b238a26fd52"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
version: "8.0.0"
flutter_staggered_grid_view:
dependency: transitive
description:
@@ -499,10 +507,10 @@ packages:
dependency: "direct main"
description:
name: http
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
url: "https://pub.dev"
source: hosted
version: "1.5.0"
version: "1.6.0"
http_multi_server:
dependency: transitive
description:
@@ -519,14 +527,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.1.2"
iconsax_flutter:
dependency: transitive
description:
name: iconsax_flutter
sha256: d14b4cec8586025ac15276bdd40f6eea308cb85748135965bb6255f14beb2564
url: "https://pub.dev"
source: hosted
version: "1.0.1"
image:
dependency: transitive
description:
@@ -635,10 +635,10 @@ packages:
dependency: transitive
description:
name: lints
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df"
url: "https://pub.dev"
source: hosted
version: "5.1.1"
version: "6.1.0"
logging:
dependency: transitive
description:
@@ -651,26 +651,26 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
url: "https://pub.dev"
source: hosted
version: "0.12.17"
version: "0.12.19"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
url: "https://pub.dev"
source: hosted
version: "0.11.1"
version: "0.13.0"
meta:
dependency: transitive
description:
name: meta
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
url: "https://pub.dev"
source: hosted
version: "1.16.0"
version: "1.18.0"
mime:
dependency: transitive
description:
@@ -683,10 +683,10 @@ packages:
dependency: "direct main"
description:
name: mobile_scanner
sha256: "0b466a0a8a211b366c2e87f3345715faef9b6011c7147556ad22f37de6ba3173"
sha256: c92c26bf2231695b6d3477c8dcf435f51e28f87b1745966b1fe4c47a286171ce
url: "https://pub.dev"
source: hosted
version: "6.0.11"
version: "7.2.0"
mutex:
dependency: "direct main"
description:
@@ -715,18 +715,18 @@ packages:
dependency: "direct main"
description:
name: package_info_plus
sha256: "16eee997588c60225bda0488b6dcfac69280a6b7a3cf02c741895dd370a02968"
sha256: "4bf625947f6c7713ee242296a682e23e44823c09cf9d79e4f1238923c92db852"
url: "https://pub.dev"
source: hosted
version: "8.3.1"
version: "10.1.0"
package_info_plus_platform_interface:
dependency: transitive
description:
name: package_info_plus_platform_interface
sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086"
sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4
url: "https://pub.dev"
source: hosted
version: "3.2.1"
version: "4.1.0"
path:
dependency: "direct main"
description:
@@ -883,34 +883,34 @@ packages:
dependency: "direct main"
description:
name: settings_ui
sha256: d9838037cb554b24b4218b2d07666fbada3478882edefae375ee892b6c820ef3
sha256: "7437c9c867f331ff6c90e951f2333441eab5cf5e654c3a7f3e4aad0c01db51ef"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
version: "3.0.1"
share_plus:
dependency: "direct main"
description:
name: share_plus
sha256: fce43200aa03ea87b91ce4c3ac79f0cecd52e2a7a56c7a4185023c271fbfa6da
sha256: a857d8b1479250aff6b57a51b2c02d31ca05848d441817c43f1640c885c286c0
url: "https://pub.dev"
source: hosted
version: "10.1.4"
version: "13.1.0"
share_plus_platform_interface:
dependency: transitive
description:
name: share_plus_platform_interface
sha256: cc012a23fc2d479854e6c80150696c4a5f5bb62cb89af4de1c505cf78d0a5d0b
sha256: "7f7ae28cf400d13f811e297ff37742dba83b79e0a6f5dce14eec0248274e6ce9"
url: "https://pub.dev"
source: hosted
version: "5.0.2"
version: "7.1.0"
shared_preferences:
dependency: "direct main"
description:
name: shared_preferences
sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5"
sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf
url: "https://pub.dev"
source: hosted
version: "2.5.3"
version: "2.5.5"
shared_preferences_android:
dependency: transitive
description:
@@ -1056,10 +1056,10 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00"
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
url: "https://pub.dev"
source: hosted
version: "0.7.6"
version: "0.7.11"
timezone:
dependency: transitive
description:
@@ -1080,10 +1080,10 @@ packages:
dependency: "direct main"
description:
name: toastification
sha256: "69db2bff425b484007409650d8bcd5ed1ce2e9666293ece74dcd917dacf23112"
sha256: "66c96678e3dece8ba24de3ea31634bd65a80aaecb8105f9bafe946e5f0d7590a"
url: "https://pub.dev"
source: hosted
version: "3.0.3"
version: "3.2.0"
typed_data:
dependency: transitive
description:
@@ -1120,10 +1120,10 @@ packages:
dependency: transitive
description:
name: url_launcher_linux
sha256: "4e9ba368772369e3e08f231d2301b4ef72b9ff87c31192ef471b380ef29a4935"
sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a
url: "https://pub.dev"
source: hosted
version: "3.2.1"
version: "3.2.2"
url_launcher_macos:
dependency: transitive
description:
@@ -1144,26 +1144,26 @@ packages:
dependency: transitive
description:
name: url_launcher_web
sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2"
sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
version: "2.4.3"
url_launcher_windows:
dependency: transitive
description:
name: url_launcher_windows
sha256: "3284b6d2ac454cf34f114e1d3319866fdd1e19cdc329999057e44ffe936cfa77"
sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f"
url: "https://pub.dev"
source: hosted
version: "3.1.4"
version: "3.1.5"
uuid:
dependency: "direct main"
description:
name: uuid
sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8
sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489"
url: "https://pub.dev"
source: hosted
version: "4.5.2"
version: "4.5.3"
vector_math:
dependency: transitive
description:
@@ -1216,18 +1216,18 @@ packages:
dependency: transitive
description:
name: win32
sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
sha256: ba6f4bba816c8d7e3c1580e170f3786d216951cc6b94babc3b814c08d2cb2738
url: "https://pub.dev"
source: hosted
version: "5.15.0"
version: "6.3.0"
win32_registry:
dependency: transitive
description:
name: win32_registry
sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae"
sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904"
url: "https://pub.dev"
source: hosted
version: "2.1.0"
version: "3.0.3"
xdg_directories:
dependency: transitive
description:
@@ -1261,5 +1261,5 @@ packages:
source: hosted
version: "3.1.3"
sdks:
dart: ">=3.9.0 <4.0.0"
flutter: ">=3.35.0"
dart: ">=3.10.0 <4.0.0"
flutter: ">=3.38.1"
+14 -14
View File
@@ -2,7 +2,7 @@ name: simplecloudnotifier
description: "Receive push messages"
publish_to: 'none'
version: 2.1.1+509
version: 2.2.8+553
environment:
sdk: '>=3.9.0 <4.0.0'
@@ -14,31 +14,31 @@ dependencies:
flutter_launcher_icons: ^0.14.3
font_awesome_flutter: '>= 4.7.0'
cupertino_icons: ^1.0.2
http: ^1.2.0
cupertino_icons: ^1.0.9
http: ^1.6.0
provider: ^6.1.1
shared_preferences: ^2.2.2
shared_preferences: ^2.5.5
qr_flutter: ^4.1.0
url_launcher: ^6.2.4
infinite_scroll_pagination: ^4.0.0
intl: ^0.20.2
path_provider: ^2.1.3
hive_flutter: ^1.1.0
package_info_plus: ^8.0.0
package_info_plus: ^10.1.0
xid: ^1.2.1
flutter_lazy_indexed_stack: ^0.0.6
flutter_lazy_indexed_stack: ^0.1.0
firebase_core: ^3.13.0
firebase_messaging: ^15.2.5
device_info_plus: ^11.3.0
toastification: ^3.0.1
uuid: ^4.4.0
share_plus: ^10.1.4
flutter_local_notifications: ^17.2.3
device_info_plus: ^13.1.0
toastification: ^3.2.0
uuid: ^4.5.3
share_plus: ^13.1.0
flutter_local_notifications: ^18.0.0
path: any
mobile_scanner: ^6.0.1
settings_ui: ^2.0.2
mobile_scanner: ^7.2.0
settings_ui: ^3.0.1
git_stamp: ^5.10.0
action_slider: ^0.7.0
mutex: ^3.1.0
@@ -52,7 +52,7 @@ dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^5.0.0
flutter_lints: ^6.0.0
hive_generator: ^2.0.1
build_runner: ^2.1.4
+1 -1
View File
@@ -17,8 +17,8 @@ simple_cloud_notifier-*.sql
identifier.sqlite
.idea/dataSources.xml
.idea/copilot*
.idea/go.imports.xml
.swaggobin
+7
View File
@@ -0,0 +1,7 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACCidGFcYZJGOE5rMRDoNC1Onx5viMJ2gSyrPKG/YK7lJwAAAJiWNW/cljVv
3AAAAAtzc2gtZWQyNTUxOQAAACCidGFcYZJGOE5rMRDoNC1Onx5viMJ2gSyrPKG/YK7lJw
AAAECzRf/pqBmG4e0SkaIYTyBkXz/zKNxP4got/q3oKkraV6J0YVxhkkY4TmsxEOg0LU6f
Hm+IwnaBLKs8ob9gruUnAAAAEnJvYmlud0BiZmIyMDIzMDAwMwECAw==
-----END OPENSSH PRIVATE KEY-----
+1
View File
@@ -0,0 +1 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKJ0YVxhkkY4TmsxEOg0LU6fHm+IwnaBLKs8ob9gruUn gnecht@bfb
+2
View File
@@ -0,0 +1,2 @@
[url "ssh://git@git.blackforestbytes.com/BlackForestBytes/goext"]
insteadOf = https://git.blackforestbytes.com/BlackForestBytes/goext
+1
View File
@@ -0,0 +1 @@
git.blackforestbytes.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDQ5uGWtRDqXF8A2FP69pPKayYYSazT+Ls/EjpNxczIpHyhpGUOvTH7GC4BMl8rBW6EVEsjPGGVIFJz3x3M1LmIwllj1+XgKQOSGdY/cRNYJDcLWMdG2eCC7gL2nIQwngMnwSs0WkIaG804X0Suq3iPftU8QRiPZTC2yTMFGbbDqF5Una8LGHzjZwZWT+pZqKh8qxVswjlrMQaS8nlCTDnB3ri4hMtp/Hc+1x/8NtvKZmBrbIgydntIN69tAavQTgAyRJIwAMy8cD8P1WizsJChlDdyI+g4WWDULgH+bA6mqrzo4YWflGpY0L1qgmPCGSSXcbb0UdNnEucpB72RPBcx
+9
View File
@@ -8,6 +8,15 @@ RUN apt-get update && \
pip install virtualenv && \
rm -rf /var/lib/apt/lists/*
# setup for private deps
RUN apt-get update && apt-get install -y --no-install-recommends git openssh-client && rm -rf /var/lib/apt/lists/*
COPY .secrets/deps-key /root/.ssh/id_ed25519
COPY .secrets/deps-key.pub /root/.ssh/id_ed25519.pub
RUN chmod 600 /root/.ssh/id_ed25519
COPY .secrets/known_hosts /root/.ssh/known_hosts
COPY .secrets/gitconfig /root/.gitconfig
ENV GOPRIVATE="git.blackforestbytes.com/*"
COPY . /buildsrc
RUN cd /buildsrc && cp "scn_send.sh" "../scn_send.sh" && make build
+8 -2
View File
@@ -119,11 +119,17 @@ func (h APIHandler) ListMessages(pctx ginext.PreContext) ginext.HTTPResponse {
}
if len(q.Search) != 0 {
filter.SearchStringFTS = langext.Ptr(langext.ArrMap(q.Search, func(v string) string { return strings.TrimSpace(v) }))
searchTerms := langext.ArrFilter(langext.ArrMap(q.Search, func(v string) string { return strings.TrimSpace(v) }), func(v string) bool { return v != "" })
if len(searchTerms) != 0 {
filter.SearchStringFTS = langext.Ptr(searchTerms)
}
}
if len(q.StringSearch) != 0 {
filter.SearchStringPlain = langext.Ptr(langext.ArrMap(q.StringSearch, func(v string) string { return strings.TrimSpace(v) }))
searchTerms := langext.ArrFilter(langext.ArrMap(q.StringSearch, func(v string) string { return strings.TrimSpace(v) }), func(v string) bool { return v != "" })
if len(searchTerms) != 0 {
filter.SearchStringPlain = langext.Ptr(searchTerms)
}
}
if len(q.Channels) != 0 {
+75 -12
View File
@@ -1,14 +1,15 @@
package handler
import (
"database/sql"
"errors"
"net/http"
"blackforestbytes.com/simplecloudnotifier/api/apierr"
"blackforestbytes.com/simplecloudnotifier/api/ginresp"
"blackforestbytes.com/simplecloudnotifier/logic"
"blackforestbytes.com/simplecloudnotifier/models"
"database/sql"
"errors"
"git.blackforestbytes.com/BlackForestBytes/goext/ginext"
"net/http"
)
// GetUserPreview swaggerdoc
@@ -52,7 +53,7 @@ func (h APIHandler) GetUserPreview(pctx ginext.PreContext) ginext.HTTPResponse {
return ginresp.APIError(g, 500, apierr.DATABASE_ERROR, "Failed to query user", err)
}
return finishSuccess(ginext.JSON(http.StatusOK, user.JSONPreview()))
return finishSuccess(ginext.JSON(http.StatusOK, user.Preview()))
})
}
@@ -92,13 +93,13 @@ func (h APIHandler) GetChannelPreview(pctx ginext.PreContext) ginext.HTTPRespons
userid := *ctx.GetPermissionUserID()
channel, err := h.database.GetChannelByID(ctx, u.ChannelID)
if errors.Is(err, sql.ErrNoRows) {
return ginresp.APIError(g, 404, apierr.CHANNEL_NOT_FOUND, "Channel not found", err)
}
channel, err := h.database.GetChannelByIDOpt(ctx, u.ChannelID)
if err != nil {
return ginresp.APIError(g, 500, apierr.DATABASE_ERROR, "Failed to query channel", err)
}
if channel == nil {
return ginresp.APIError(g, 404, apierr.CHANNEL_NOT_FOUND, "Channel not found", err)
}
sub, err := h.database.GetSubscriptionBySubscriber(ctx, userid, channel.ChannelID)
if err != nil {
@@ -161,13 +162,13 @@ func (h APIHandler) GetUserKeyPreview(pctx ginext.PreContext) ginext.HTTPRespons
// Query by token.token
keytoken, err := h.database.GetKeyTokenByToken(ctx, u.KeyID)
if keytoken == nil {
return ginresp.APIError(g, 404, apierr.KEY_NOT_FOUND, "Key not found", err)
}
keytoken, err := h.database.GetKeyTokenByTokenOpt(ctx, u.KeyID)
if err != nil {
return ginresp.APIError(g, 500, apierr.DATABASE_ERROR, "Failed to query client", err)
}
if keytoken == nil {
return ginresp.APIError(g, 404, apierr.KEY_NOT_FOUND, "Key not found", err)
}
return finishSuccess(ginext.JSON(http.StatusOK, keytoken.Preview()))
@@ -175,3 +176,65 @@ func (h APIHandler) GetUserKeyPreview(pctx ginext.PreContext) ginext.HTTPRespons
})
}
// GetClientPreview swaggerdoc
//
// @Summary Get a client (similar to api-clients-get, but can be called from anyone and only returns a subset of fields)
// @ID api-clients-get-preview
// @Tags API-v2
//
// @Param cid path string true "ClientID"
//
// @Success 200 {object} handler.GetClientPreview.response
//
// @Failure 400 {object} ginresp.apiError "supplied values/parameters cannot be parsed / are invalid"
// @Failure 401 {object} ginresp.apiError "user is not authorized / has missing permissions"
// @Failure 404 {object} ginresp.apiError "client not found"
// @Failure 500 {object} ginresp.apiError "internal server error"
//
// @Router /api/v2/preview/clients/{cid} [GET]
func (h APIHandler) GetClientPreview(pctx ginext.PreContext) ginext.HTTPResponse {
type uri struct {
ClientID models.ClientID `uri:"cid" binding:"entityid"`
}
type response struct {
Client models.ClientPreview `json:"client"`
User models.UserPreview `json:"user"`
}
var u uri
ctx, g, errResp := pctx.URI(&u).Start()
if errResp != nil {
return *errResp
}
defer ctx.Cancel()
return h.app.DoRequest(ctx, g, models.TLockRead, func(ctx *logic.AppContext, finishSuccess func(r ginext.HTTPResponse) ginext.HTTPResponse) ginext.HTTPResponse {
if permResp := ctx.CheckPermissionAny(); permResp != nil {
return *permResp
}
client, err := h.database.GetClientByIDOpt(ctx, u.ClientID)
if err != nil {
return ginresp.APIError(g, 500, apierr.DATABASE_ERROR, "Failed to query client", err)
}
if client == nil {
return ginresp.APIError(g, 404, apierr.CLIENT_NOT_FOUND, "Client not found", err)
}
user, err := h.database.GetUser(ctx, client.UserID)
if errors.Is(err, sql.ErrNoRows) {
return ginresp.APIError(g, 404, apierr.USER_NOT_FOUND, "User not found", err)
}
if err != nil {
return ginresp.APIError(g, 500, apierr.DATABASE_ERROR, "Failed to query user", err)
}
return finishSuccess(ginext.JSON(http.StatusOK, response{
Client: client.Preview(),
User: user.Preview(),
}))
})
}
+1 -1
View File
@@ -362,7 +362,7 @@ func (h APIHandler) CreateSubscription(pctx ginext.PreContext) ginext.HTTPRespon
} else if b.ChannelOwnerUserID == nil && b.ChannelInternalName == nil && b.ChannelID != nil {
outchannel, err := h.database.GetChannelByID(ctx, *b.ChannelID)
outchannel, err := h.database.GetChannelByIDOpt(ctx, *b.ChannelID)
if err != nil {
return ginresp.APIError(g, 500, apierr.DATABASE_ERROR, "Failed to query channel", err)
}
+6 -6
View File
@@ -305,7 +305,7 @@ func (h CompatHandler) Info(pctx ginext.PreContext) ginext.HTTPResponse {
return ginresp.CompatAPIError(0, "Failed to query user")
}
keytok, err := h.database.GetKeyTokenByToken(ctx, *data.UserKey)
keytok, err := h.database.GetKeyTokenByTokenOpt(ctx, *data.UserKey)
if err != nil {
return ginresp.CompatAPIError(0, "Failed to query token")
}
@@ -417,7 +417,7 @@ func (h CompatHandler) Ack(pctx ginext.PreContext) ginext.HTTPResponse {
return ginresp.CompatAPIError(0, "Failed to query user")
}
keytok, err := h.database.GetKeyTokenByToken(ctx, *data.UserKey)
keytok, err := h.database.GetKeyTokenByTokenOpt(ctx, *data.UserKey)
if err != nil {
return ginresp.CompatAPIError(0, "Failed to query token")
}
@@ -523,7 +523,7 @@ func (h CompatHandler) Requery(pctx ginext.PreContext) ginext.HTTPResponse {
return ginresp.CompatAPIError(0, "Failed to query user")
}
keytok, err := h.database.GetKeyTokenByToken(ctx, *data.UserKey)
keytok, err := h.database.GetKeyTokenByTokenOpt(ctx, *data.UserKey)
if err != nil {
return ginresp.CompatAPIError(0, "Failed to query token")
}
@@ -644,7 +644,7 @@ func (h CompatHandler) Update(pctx ginext.PreContext) ginext.HTTPResponse {
return ginresp.CompatAPIError(0, "Failed to query user")
}
keytok, err := h.database.GetKeyTokenByToken(ctx, *data.UserKey)
keytok, err := h.database.GetKeyTokenByTokenOpt(ctx, *data.UserKey)
if err != nil {
return ginresp.CompatAPIError(0, "Failed to query token")
}
@@ -778,7 +778,7 @@ func (h CompatHandler) Expand(pctx ginext.PreContext) ginext.HTTPResponse {
return ginresp.CompatAPIError(0, "Failed to query user")
}
keytok, err := h.database.GetKeyTokenByToken(ctx, *data.UserKey)
keytok, err := h.database.GetKeyTokenByTokenOpt(ctx, *data.UserKey)
if err != nil {
return ginresp.CompatAPIError(0, "Failed to query token")
}
@@ -901,7 +901,7 @@ func (h CompatHandler) Upgrade(pctx ginext.PreContext) ginext.HTTPResponse {
return ginresp.CompatAPIError(0, "Failed to query user")
}
keytok, err := h.database.GetKeyTokenByToken(ctx, *data.UserKey)
keytok, err := h.database.GetKeyTokenByTokenOpt(ctx, *data.UserKey)
if err != nil {
return ginresp.CompatAPIError(0, "Failed to query token")
}
+1 -1
View File
@@ -148,7 +148,7 @@ func (h ExternalHandler) UptimeKuma(pctx ginext.PreContext) ginext.HTTPResponse
// @Tags External
//
// @Param query_data query handler.Shoutrrr.query false " "
// @Param post_body body handler.Shoutrrr.body false " "
// @Param post_body body handler.Shoutrrr.body false " "
//
// @Success 200 {object} handler.Shoutrrr.response
// @Failure 400 {object} ginresp.apiError
+1
View File
@@ -171,6 +171,7 @@ func (r *Router) Init(e *ginext.GinWrapper) error {
apiv2.GET("/preview/users/:uid").Handle(r.apiHandler.GetUserPreview)
apiv2.GET("/preview/keys/:kid").Handle(r.apiHandler.GetUserKeyPreview)
apiv2.GET("/preview/channels/:cid").Handle(r.apiHandler.GetChannelPreview)
apiv2.GET("/preview/clients/:cid").Handle(r.apiHandler.GetClientPreview)
}
// ================ Send API (unversioned) ================
+3 -2
View File
@@ -1,10 +1,11 @@
package primary
import (
"time"
"blackforestbytes.com/simplecloudnotifier/db"
"blackforestbytes.com/simplecloudnotifier/models"
"git.blackforestbytes.com/BlackForestBytes/goext/sq"
"time"
)
func (db *Database) GetChannelByName(ctx db.TxContext, userid models.UserID, chanName string) (*models.Channel, error) {
@@ -16,7 +17,7 @@ func (db *Database) GetChannelByName(ctx db.TxContext, userid models.UserID, cha
return sq.QuerySingleOpt[models.Channel](ctx, tx, "SELECT * FROM channels WHERE owner_user_id = :uid AND internal_name = :nam AND deleted=0 LIMIT 1", sq.PP{"uid": userid, "nam": chanName}, sq.SModeExtended, sq.Safe)
}
func (db *Database) GetChannelByID(ctx db.TxContext, chanid models.ChannelID) (*models.Channel, error) {
func (db *Database) GetChannelByIDOpt(ctx db.TxContext, chanid models.ChannelID) (*models.Channel, error) {
tx, err := ctx.GetOrCreateTransaction(db)
if err != nil {
return nil, err
+9
View File
@@ -53,6 +53,15 @@ func (db *Database) GetClient(ctx db.TxContext, userid models.UserID, clientid m
}, sq.SModeExtended, sq.Safe)
}
func (db *Database) GetClientByIDOpt(ctx db.TxContext, clientid models.ClientID) (*models.Client, error) {
tx, err := ctx.GetOrCreateTransaction(db)
if err != nil {
return nil, err
}
return sq.QuerySingleOpt[models.Client](ctx, tx, "SELECT * FROM clients WHERE deleted=0 AND client_id = :cid LIMIT 1", sq.PP{"cid": clientid}, sq.SModeExtended, sq.Safe)
}
func (db *Database) GetClientOpt(ctx db.TxContext, userid models.UserID, clientid models.ClientID) (*models.Client, error) {
tx, err := ctx.GetOrCreateTransaction(db)
if err != nil {
+4 -3
View File
@@ -1,12 +1,13 @@
package primary
import (
"strings"
"time"
"blackforestbytes.com/simplecloudnotifier/db"
"blackforestbytes.com/simplecloudnotifier/models"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"git.blackforestbytes.com/BlackForestBytes/goext/sq"
"strings"
"time"
)
func (db *Database) CreateKeyToken(ctx db.TxContext, name string, owner models.UserID, allChannels bool, channels []models.ChannelID, permissions models.TokenPermissionList, token string) (models.KeyToken, error) {
@@ -67,7 +68,7 @@ func (db *Database) GetKeyTokenByID(ctx db.TxContext, keyTokenid models.KeyToken
return sq.QuerySingle[models.KeyToken](ctx, tx, "SELECT * FROM keytokens WHERE keytoken_id = :cid AND deleted=0 LIMIT 1", sq.PP{"cid": keyTokenid}, sq.SModeExtended, sq.Safe)
}
func (db *Database) GetKeyTokenByToken(ctx db.TxContext, key string) (*models.KeyToken, error) {
func (db *Database) GetKeyTokenByTokenOpt(ctx db.TxContext, key string) (*models.KeyToken, error) {
tx, err := ctx.GetOrCreateTransaction(db)
if err != nil {
return nil, err
+5 -4
View File
@@ -1,14 +1,15 @@
package jobs
import (
"errors"
"fmt"
"time"
"blackforestbytes.com/simplecloudnotifier/db/simplectx"
"blackforestbytes.com/simplecloudnotifier/logic"
"blackforestbytes.com/simplecloudnotifier/models"
"errors"
"fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/syncext"
"github.com/rs/zerolog/log"
"time"
)
type DeliveryRetryJob struct {
@@ -208,7 +209,7 @@ func (j *DeliveryRetryJob) redeliver(ctx *simplectx.SimpleContext, delivery mode
return
}
channel, err := j.app.Database.Primary.GetChannelByID(ctx, msg.ChannelID)
channel, err := j.app.Database.Primary.GetChannelByIDOpt(ctx, msg.ChannelID)
if err != nil {
log.Err(err).Str("ChannelID", msg.ChannelID.String()).Msg("Failed to get channel")
ctx.RollbackTransaction()
+1 -1
View File
@@ -245,7 +245,7 @@ func (app *Application) getPermissions(ctx db.TxContext, hdr string) (models.Per
key := strings.TrimSpace(hdr[4:])
tok, err := app.Database.Primary.GetKeyTokenByToken(ctx, key)
tok, err := app.Database.Primary.GetKeyTokenByTokenOpt(ctx, key)
if err != nil {
return models.PermissionSet{}, err
}
+1 -1
View File
@@ -75,7 +75,7 @@ func (ac *AppContext) CheckPermissionUserAdmin(userid models.UserID) *ginext.HTT
func (ac *AppContext) CheckPermissionSend(channel models.Channel, key string) (*models.KeyToken, *ginext.HTTPResponse) {
keytok, err := ac.app.Database.Primary.GetKeyTokenByToken(ac, key)
keytok, err := ac.app.Database.Primary.GetKeyTokenByTokenOpt(ac, key)
if err != nil {
return nil, langext.Ptr(ginresp.APIError(ac.ginContext, 500, apierr.DATABASE_ERROR, "Failed to query token", err))
}
+22
View File
@@ -21,3 +21,25 @@ type Client struct {
Name *string `db:"name" json:"name"`
Deleted bool `db:"deleted" json:"-"`
}
type ClientPreview struct {
ClientID ClientID `json:"client_id"`
UserID UserID `json:"user_id"`
Type ClientType `json:"type"`
TimestampCreated SCNTime `json:"timestamp_created"`
AgentModel string `json:"agent_model"`
AgentVersion string `json:"agent_version"`
Name *string `json:"name"`
}
func (c Client) Preview() ClientPreview {
return ClientPreview{
ClientID: c.ClientID,
UserID: c.UserID,
Type: c.Type,
TimestampCreated: c.TimestampCreated,
AgentModel: c.AgentModel,
AgentVersion: c.AgentVersion,
Name: c.Name,
}
}
+43 -4
View File
@@ -4,13 +4,15 @@ import (
"crypto/sha512"
"encoding/hex"
"fmt"
"strconv"
"strings"
"time"
"unicode"
"git.blackforestbytes.com/BlackForestBytes/goext/dataext"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"git.blackforestbytes.com/BlackForestBytes/goext/mathext"
"git.blackforestbytes.com/BlackForestBytes/goext/sq"
"strconv"
"strings"
"time"
)
type MessageFilter struct {
@@ -219,7 +221,7 @@ func (f MessageFilter) SQL() (string, string, sq.PP, error) {
if f.SearchStringFTS != nil {
filter := make([]string, 0)
for _, v := range *f.SearchStringFTS {
filter = append(filter, fmt.Sprintf("(messages_fts match :%s)", params.Add(v)))
filter = append(filter, fmt.Sprintf("(messages_fts match :%s)", params.Add(sanitizeFTSMatchQuery(v))))
}
sqlClauses = append(sqlClauses, "("+strings.Join(filter, " OR ")+")")
}
@@ -246,6 +248,43 @@ func (f MessageFilter) SQL() (string, string, sq.PP, error) {
return sqlClause, joinClause, params, nil
}
// sanitizeFTSMatchQuery converts an arbitrary user-provided search string into a valid FTS5 MATCH query.
// It preserves explicit "quoted phrases" typed by the user and wraps every other whitespace-separated word
// in double-quotes, so that FTS5 special characters ( - : * ^ ( ) AND OR NOT NEAR ... ) inside plain search
// terms are treated as literal text instead of query operators.
func sanitizeFTSMatchQuery(s string) string {
out := make([]string, 0)
buf := strings.Builder{}
inQuote := false
flush := func() {
if buf.Len() > 0 {
out = append(out, `"`+strings.ReplaceAll(buf.String(), `"`, `""`)+`"`)
buf.Reset()
}
}
for _, r := range s {
switch {
case r == '"':
// a double-quote opens or closes an explicit phrase; flush the pending word either way
flush()
inQuote = !inQuote
case !inQuote && unicode.IsSpace(r):
flush()
default:
buf.WriteRune(r)
}
}
flush() // trailing word or an unterminated phrase
if len(out) == 0 {
return `""` // valid FTS5 query that simply matches nothing
}
return strings.Join(out, " ")
}
func (f MessageFilter) Hash() string {
bh, err := dataext.StructHash(f, dataext.StructHashOptions{HashAlgo: sha512.New()})
if err != nil {
+3 -3
View File
@@ -88,9 +88,9 @@ func (u User) MaxTitleLength() int {
func (u User) QuotaPerDay() int {
if u.IsPro {
return 5000
return 15_000
} else {
return 50
return 500
}
}
@@ -135,7 +135,7 @@ func (u User) MaxTimestampDiffHours() int {
return 24
}
func (u User) JSONPreview() UserPreview {
func (u User) Preview() UserPreview {
return UserPreview{
UserID: u.UserID,
Username: u.Username,
+13 -6
View File
@@ -1,22 +1,23 @@
package push
import (
scn "blackforestbytes.com/simplecloudnotifier"
"blackforestbytes.com/simplecloudnotifier/models"
"bytes"
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
"io"
"net/http"
"strconv"
"strings"
"time"
scn "blackforestbytes.com/simplecloudnotifier"
"blackforestbytes.com/simplecloudnotifier/models"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
)
// https://firebase.google.com/docs/cloud-messaging/send-message#rest
@@ -66,7 +67,13 @@ func (fb FirebaseConnector) SendNotification(ctx context.Context, user models.Us
"title": msg.Title,
"body": msg.ShortContent(),
},
"apns": gin.H{},
"apns": gin.H{
"payload": gin.H{
"aps": gin.H{
"sound": "default",
},
},
},
}
} else if client.Type == models.ClientTypeAndroid {
jsonBody = gin.H{
+12 -11
View File
@@ -1,13 +1,14 @@
package test
import (
"blackforestbytes.com/simplecloudnotifier/push"
tt "blackforestbytes.com/simplecloudnotifier/test/util"
"fmt"
"github.com/gin-gonic/gin"
"net/url"
"testing"
"time"
"blackforestbytes.com/simplecloudnotifier/push"
tt "blackforestbytes.com/simplecloudnotifier/test/util"
"github.com/gin-gonic/gin"
)
func TestSendCompatWithOldUser(t *testing.T) {
@@ -309,7 +310,7 @@ func TestCompatRegister(t *testing.T) {
tt.AssertEqual(t, "success", true, r0["success"])
tt.AssertEqual(t, "message", "New user registered", r0["message"])
tt.AssertEqual(t, "quota", 0, r0["quota"])
tt.AssertEqual(t, "quota_max", 50, r0["quota_max"])
tt.AssertEqual(t, "quota_max", 500, r0["quota_max"])
tt.AssertEqual(t, "is_pro", false, r0["is_pro"])
}
@@ -321,7 +322,7 @@ func TestCompatRegisterPro(t *testing.T) {
tt.AssertEqual(t, "success", true, r0["success"])
tt.AssertEqual(t, "message", "New user registered", r0["message"])
tt.AssertEqual(t, "quota", 0, r0["quota"])
tt.AssertEqual(t, "quota_max", 5000, r0["quota_max"])
tt.AssertEqual(t, "quota_max", 15000, r0["quota_max"])
tt.AssertEqual(t, "is_pro", true, r0["is_pro"])
r1 := tt.RequestGet[gin.H](t, baseUrl, fmt.Sprintf("/api/register.php?fcm_token=%s&pro=%s&pro_token=%s", "DUMMY_FCM", "true", url.QueryEscape("INVALID")))
@@ -345,7 +346,7 @@ func TestCompatInfo(t *testing.T) {
tt.AssertEqual(t, "is_pro", 0, r1["is_pro"])
tt.AssertEqual(t, "message", "ok", r1["message"])
tt.AssertEqual(t, "quota", 0, r1["quota"])
tt.AssertEqual(t, "quota_max", 50, r1["quota_max"])
tt.AssertEqual(t, "quota_max", 500, r1["quota_max"])
tt.AssertEqual(t, "unack_count", 0, r1["unack_count"])
tt.AssertEqual(t, "user_id", userid, r1["user_id"])
tt.AssertEqual(t, "user_key", userkey, r1["user_key"])
@@ -363,7 +364,7 @@ func TestCompatInfo(t *testing.T) {
tt.AssertEqual(t, "is_pro", 0, r2["is_pro"])
tt.AssertEqual(t, "message", "ok", r2["message"])
tt.AssertEqual(t, "quota", 1, r2["quota"])
tt.AssertEqual(t, "quota_max", 50, r2["quota_max"])
tt.AssertEqual(t, "quota_max", 500, r2["quota_max"])
tt.AssertEqual(t, "unack_count", 1, r2["unack_count"])
tt.AssertEqual(t, "user_id", userid, r2["user_id"])
tt.AssertEqual(t, "user_key", userkey, r2["user_key"])
@@ -490,7 +491,7 @@ func TestCompatUpdateUserKey(t *testing.T) {
tt.AssertEqual(t, "is_pro", 0, r1["is_pro"])
tt.AssertEqual(t, "message", "ok", r1["message"])
tt.AssertEqual(t, "quota", 1, r1["quota"])
tt.AssertEqual(t, "quota_max", 50, r1["quota_max"])
tt.AssertEqual(t, "quota_max", 500, r1["quota_max"])
tt.AssertEqual(t, "unack_count", 1, r1["unack_count"])
tt.AssertEqual(t, "user_id", userid, r1["user_id"])
tt.AssertEqual(t, "user_key", newkey, r1["user_key"])
@@ -527,7 +528,7 @@ func TestCompatUpdateFCM(t *testing.T) {
tt.AssertEqual(t, "is_pro", 0, r1["is_pro"])
tt.AssertEqual(t, "message", "ok", r1["message"])
tt.AssertEqual(t, "quota", 1, r1["quota"])
tt.AssertEqual(t, "quota_max", 50, r1["quota_max"])
tt.AssertEqual(t, "quota_max", 500, r1["quota_max"])
tt.AssertEqual(t, "unack_count", 1, r1["unack_count"])
tt.AssertEqual(t, "user_id", userid, r1["user_id"])
tt.AssertEqual(t, "user_key", newkey, r1["user_key"])
@@ -554,7 +555,7 @@ func TestCompatUpgrade(t *testing.T) {
tt.AssertEqual(t, "success", true, r0["success"])
tt.AssertEqual(t, "message", "New user registered", r0["message"])
tt.AssertEqual(t, "quota", 0, r0["quota"])
tt.AssertEqual(t, "quota_max", 50, r0["quota_max"])
tt.AssertEqual(t, "quota_max", 500, r0["quota_max"])
tt.AssertEqual(t, "is_pro", false, r0["is_pro"])
userid := int64(r0["user_id"].(float64))
@@ -564,7 +565,7 @@ func TestCompatUpgrade(t *testing.T) {
tt.AssertEqual(t, "success", true, r1["success"])
tt.AssertEqual(t, "message", "user updated", r1["message"])
tt.AssertEqual(t, "quota", 0, r1["quota"])
tt.AssertEqual(t, "quota_max", 5000, r1["quota_max"])
tt.AssertEqual(t, "quota_max", 15000, r1["quota_max"])
tt.AssertEqual(t, "is_pro", true, r1["is_pro"])
}
+5
View File
@@ -830,6 +830,11 @@ func TestListMessagesSearch(t *testing.T) {
{"search=the(2)", 17, fmt.Sprintf("/api/v2/messages?search=%s", url.QueryEscape("THE"))},
{"search=please", 9, fmt.Sprintf("/api/v2/messages?search=%s", url.QueryEscape("please"))},
{"search=11pm", 2, fmt.Sprintf("/api/v2/messages?search=%s", url.QueryEscape("\"11:00pm\""))},
{"search=hyphen", 0, fmt.Sprintf("/api/v2/messages?search=%s", url.QueryEscape("yt-backup"))},
{"search=colon", 0, fmt.Sprintf("/api/v2/messages?search=%s", url.QueryEscape("foo:bar"))},
{"search=NOT", 0, fmt.Sprintf("/api/v2/messages?search=%s", url.QueryEscape("NOT"))},
{"search=empty", 22, fmt.Sprintf("/api/v2/messages?search=%s", url.QueryEscape(""))},
}
for _, testdata := range filterTests {
+7 -4
View File
@@ -1,14 +1,15 @@
package test
import (
ct "blackforestbytes.com/simplecloudnotifier/db/cursortoken"
"blackforestbytes.com/simplecloudnotifier/models"
tt "blackforestbytes.com/simplecloudnotifier/test/util"
"fmt"
"github.com/gin-gonic/gin"
"net/url"
"testing"
"time"
ct "blackforestbytes.com/simplecloudnotifier/db/cursortoken"
"blackforestbytes.com/simplecloudnotifier/models"
tt "blackforestbytes.com/simplecloudnotifier/test/util"
"github.com/gin-gonic/gin"
)
func TestRequestLogSimple(t *testing.T) {
@@ -126,6 +127,8 @@ func TestRequestLogSimple(t *testing.T) {
}
func TestRequestLogAPI(t *testing.T) {
t.Skip("Flaky test - and kinda hacky")
ws, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
+30 -26
View File
@@ -1159,6 +1159,8 @@ func TestSendToTooLongChannel(t *testing.T) {
}
func TestQuotaExceededNoPro(t *testing.T) {
t.Skip("takes too long on server")
_, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
@@ -1174,8 +1176,8 @@ func TestQuotaExceededNoPro(t *testing.T) {
sendtok := r0["send_key"].(string)
tt.AssertStrRepEqual(t, "quota.0", 0, r0["quota_used"])
tt.AssertStrRepEqual(t, "quota.0", 50, r0["quota_max"])
tt.AssertStrRepEqual(t, "quota.0", 50, r0["quota_remaining"])
tt.AssertStrRepEqual(t, "quota.0", 500, r0["quota_max"])
tt.AssertStrRepEqual(t, "quota.0", 500, r0["quota_remaining"])
{
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
@@ -1184,18 +1186,18 @@ func TestQuotaExceededNoPro(t *testing.T) {
"title": tt.ShortLipsum0(2),
})
tt.AssertStrRepEqual(t, "quota.msg.1", 1, msg1["quota"])
tt.AssertStrRepEqual(t, "quota.msg.1", 50, msg1["quota_max"])
tt.AssertStrRepEqual(t, "quota.msg.1", 500, msg1["quota_max"])
}
{
usr := tt.RequestAuthGet[gin.H](t, admintok, baseUrl, fmt.Sprintf("/api/v2/users/%s", uid))
tt.AssertStrRepEqual(t, "quota.1", 1, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.1", 50, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.1", 49, usr["quota_remaining"])
tt.AssertStrRepEqual(t, "quota.1", 500, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.1", 499, usr["quota_remaining"])
}
for i := 0; i < 48; i++ {
for i := 0; i < 498; i++ {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
@@ -1207,24 +1209,24 @@ func TestQuotaExceededNoPro(t *testing.T) {
{
usr := tt.RequestAuthGet[gin.H](t, admintok, baseUrl, fmt.Sprintf("/api/v2/users/%s", uid))
tt.AssertStrRepEqual(t, "quota.49", 49, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.49", 50, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.49", 499, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.49", 500, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.49", 1, usr["quota_remaining"])
}
msg50 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
msg500 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": tt.ShortLipsum0(2),
})
tt.AssertStrRepEqual(t, "quota.msg.50", 50, msg50["quota"])
tt.AssertStrRepEqual(t, "quota.msg.50", 50, msg50["quota_max"])
tt.AssertStrRepEqual(t, "quota.msg.50", 500, msg500["quota"])
tt.AssertStrRepEqual(t, "quota.msg.50", 500, msg500["quota_max"])
{
usr := tt.RequestAuthGet[gin.H](t, admintok, baseUrl, fmt.Sprintf("/api/v2/users/%s", uid))
tt.AssertStrRepEqual(t, "quota.50", 50, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.50", 50, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.50", 500, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.50", 500, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.50", 0, usr["quota_remaining"])
}
@@ -1236,6 +1238,8 @@ func TestQuotaExceededNoPro(t *testing.T) {
}
func TestQuotaExceededPro(t *testing.T) {
t.Skip("takes too long on server")
_, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
@@ -1252,8 +1256,8 @@ func TestQuotaExceededPro(t *testing.T) {
sendtok := r0["send_key"].(string)
tt.AssertStrRepEqual(t, "quota.0", 0, r0["quota_used"])
tt.AssertStrRepEqual(t, "quota.0", 5000, r0["quota_max"])
tt.AssertStrRepEqual(t, "quota.0", 5000, r0["quota_remaining"])
tt.AssertStrRepEqual(t, "quota.0", 15000, r0["quota_max"])
tt.AssertStrRepEqual(t, "quota.0", 15000, r0["quota_remaining"])
{
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
@@ -1262,18 +1266,18 @@ func TestQuotaExceededPro(t *testing.T) {
"title": tt.ShortLipsum0(2),
})
tt.AssertStrRepEqual(t, "quota.msg.1", 1, msg1["quota"])
tt.AssertStrRepEqual(t, "quota.msg.1", 5000, msg1["quota_max"])
tt.AssertStrRepEqual(t, "quota.msg.1", 15000, msg1["quota_max"])
}
{
usr := tt.RequestAuthGet[gin.H](t, admintok, baseUrl, fmt.Sprintf("/api/v2/users/%s", uid))
tt.AssertStrRepEqual(t, "quota.1", 1, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.1", 5000, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.1", 4999, usr["quota_remaining"])
tt.AssertStrRepEqual(t, "quota.1", 15000, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.1", 14999, usr["quota_remaining"])
}
for i := 0; i < 4998; i++ {
for i := 0; i < 14998; i++ {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
@@ -1285,9 +1289,9 @@ func TestQuotaExceededPro(t *testing.T) {
{
usr := tt.RequestAuthGet[gin.H](t, admintok, baseUrl, fmt.Sprintf("/api/v2/users/%s", uid))
tt.AssertStrRepEqual(t, "quota.999", 4999, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.999", 5000, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.999", 1, usr["quota_remaining"])
tt.AssertStrRepEqual(t, "quota.14999", 14999, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.14999", 15000, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.14999", 1, usr["quota_remaining"])
}
msg50 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
@@ -1295,14 +1299,14 @@ func TestQuotaExceededPro(t *testing.T) {
"user_id": uid,
"title": tt.ShortLipsum0(2),
})
tt.AssertStrRepEqual(t, "quota.msg.5000", 5000, msg50["quota"])
tt.AssertStrRepEqual(t, "quota.msg.5000", 5000, msg50["quota_max"])
tt.AssertStrRepEqual(t, "quota.msg.5000", 15000, msg50["quota"])
tt.AssertStrRepEqual(t, "quota.msg.5000", 15000, msg50["quota_max"])
{
usr := tt.RequestAuthGet[gin.H](t, admintok, baseUrl, fmt.Sprintf("/api/v2/users/%s", uid))
tt.AssertStrRepEqual(t, "quota.5000", 5000, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.5000", 5000, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.5000", 15000, usr["quota_used"])
tt.AssertStrRepEqual(t, "quota.5000", 15000, usr["quota_max"])
tt.AssertStrRepEqual(t, "quota.5000", 0, usr["quota_remaining"])
}
+7 -6
View File
@@ -1,11 +1,12 @@
package test
import (
"fmt"
"testing"
"blackforestbytes.com/simplecloudnotifier/api/apierr"
tt "blackforestbytes.com/simplecloudnotifier/test/util"
"fmt"
"github.com/gin-gonic/gin"
"testing"
)
func TestCreateUserNoClient(t *testing.T) {
@@ -451,8 +452,8 @@ func TestGetUserNoPro(t *testing.T) {
tt.AssertEqual(t, "timestamp_lastsent", nil, r1["timestamp_lastsent"])
tt.AssertEqual(t, "messages_sent", "0", fmt.Sprintf("%v", r1["messages_sent"]))
tt.AssertEqual(t, "quota_used", "0", fmt.Sprintf("%v", r1["quota_used"]))
tt.AssertEqual(t, "quota_remaining", "50", fmt.Sprintf("%v", r1["quota_remaining"]))
tt.AssertEqual(t, "quota_max", "50", fmt.Sprintf("%v", r1["quota_max"]))
tt.AssertEqual(t, "quota_remaining", "500", fmt.Sprintf("%v", r1["quota_remaining"]))
tt.AssertEqual(t, "quota_max", "500", fmt.Sprintf("%v", r1["quota_max"]))
tt.AssertEqual(t, "is_pro", "false", fmt.Sprintf("%v", r1["is_pro"]))
tt.AssertEqual(t, "default_channel", "main", fmt.Sprintf("%v", r1["default_channel"]))
tt.AssertEqual(t, "max_body_size", "2048", fmt.Sprintf("%v", r1["max_body_size"]))
@@ -485,8 +486,8 @@ func TestGetUserPro(t *testing.T) {
tt.AssertEqual(t, "timestamp_lastsent", nil, r1["timestamp_lastsent"])
tt.AssertEqual(t, "messages_sent", "0", fmt.Sprintf("%v", r1["messages_sent"]))
tt.AssertEqual(t, "quota_used", "0", fmt.Sprintf("%v", r1["quota_used"]))
tt.AssertEqual(t, "quota_remaining", "5000", fmt.Sprintf("%v", r1["quota_remaining"]))
tt.AssertEqual(t, "quota_max", "5000", fmt.Sprintf("%v", r1["quota_max"]))
tt.AssertEqual(t, "quota_remaining", "15000", fmt.Sprintf("%v", r1["quota_remaining"]))
tt.AssertEqual(t, "quota_max", "15000", fmt.Sprintf("%v", r1["quota_max"]))
tt.AssertEqual(t, "is_pro", "true", fmt.Sprintf("%v", r1["is_pro"]))
tt.AssertEqual(t, "default_channel", "main", fmt.Sprintf("%v", r1["default_channel"]))
tt.AssertEqual(t, "max_body_size", "2097152", fmt.Sprintf("%d", (int64)(r1["max_body_size"].(float64))))
+4 -2
View File
@@ -3,13 +3,14 @@ package util
import (
"encoding/json"
"fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/gin-gonic/gin"
"math"
"reflect"
"runtime/debug"
"strings"
"testing"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/gin-gonic/gin"
)
func AssertJsonMapEqual(t *testing.T, key string, expected map[string]any, actual map[string]any) {
@@ -36,6 +37,7 @@ func AssertJsonMapEqual(t *testing.T, key string, expected map[string]any, actua
}
func AssertEqual(t *testing.T, key string, expected any, actual any) {
t.Helper()
// try to fix types, kinda hacky, but its only unit tests...
switch vex := expected.(type) {
+23
View File
@@ -128,6 +128,29 @@ body
text-align: center;
}
#tr_links
{
position: absolute;
top: 0;
right: 0;
margin: -1px -1px 0 0;
display: flex;
gap: 1rem;
align-items: flex-start;
}
#tr_links .edge-btn
{
position: static;
margin: 0;
}
#tr_link_web
{
min-width: 40px;
text-align: center;
}
#tl_link1
{
top: 0;
+4 -1
View File
@@ -17,7 +17,10 @@
<a tabindex="-1" href="https://play.google.com/store/apps/details?id=com.blackforestbytes.simplecloudnotifier" class="button bordered edge-btn" id="tl_link1"><span class="icn-google-play"></span></a>
<a tabindex="-1" href="https://apps.apple.com/us/app/simplecloudnotifier/id6455594868" class="button bordered edge-btn" id="tl_link2"><span class="icn-app-store"></span></a>
<a tabindex="-1" href="/api" class="button bordered edge-btn" id="tr_link">API</a>
<div id="tr_links">
<a tabindex="-1" href="https://app.simplecloudnotifier.de" class="button bordered edge-btn" id="tr_link_web">Web</a>
<a tabindex="-1" href="/api" class="button bordered edge-btn" id="tr_link">API</a>
</div>
<a tabindex="-1" href="/" class="linkcaption"><h1>Simple Cloud Notifier</h1></a>
+2
View File
@@ -45,6 +45,7 @@ import {
PlayCircleOutline,
StopOutline,
ArrowLeftOutline,
DownOutline,
} from '@ant-design/icons-angular/icons';
import { routes } from './app.routes';
@@ -91,6 +92,7 @@ const icons: IconDefinition[] = [
PlayCircleOutline,
StopOutline,
ArrowLeftOutline,
DownOutline,
];
export const appConfig: ApplicationConfig = {
@@ -21,6 +21,9 @@ export interface ChannelPreview {
owner_user_id: string;
internal_name: string;
display_name: string;
description_name: string | null;
messages_sent: number;
subscription: Subscription | null;
}
export type ChannelSelector = 'owned' | 'subscribed' | 'all' | 'subscribed_any' | 'all_any';
@@ -1,3 +1,5 @@
import { UserPreview } from "./user.model";
export type ClientType = 'ANDROID' | 'IOS' | 'LINUX' | 'MACOS' | 'WINDOWS';
export interface Client {
@@ -15,6 +17,21 @@ export interface ClientListResponse {
clients: Client[];
}
export interface ClientPreview {
client_id: string;
user_id: string;
name: string | null;
type: ClientType;
timestamp_created: string;
agent_model: string;
agent_version: string;
}
export interface ClientPreviewResponse {
user: UserPreview;
client: ClientPreview;
}
export function getClientTypeIcon(type: ClientType): string {
switch (type) {
case 'ANDROID':
@@ -14,6 +14,10 @@ export interface KeyToken {
export interface KeyTokenPreview {
keytoken_id: string;
name: string;
owner_user_id: string;
all_channels: boolean;
channels: string[];
permissions: string;
}
export type TokenPermission = 'A' | 'CR' | 'CS' | 'UR';
@@ -6,6 +6,8 @@ import {
User,
UserWithExtra,
UserPreview,
ChannelPreview,
KeyTokenPreview,
Message,
MessageListParams,
MessageListResponse,
@@ -26,6 +28,7 @@ import {
UpdateKeyRequest,
Client,
ClientListResponse,
ClientPreviewResponse,
SenderNameStatistics,
SenderNameListResponse,
DeliveryListResponse,
@@ -93,6 +96,18 @@ export class ApiService {
return this.http.delete<Client>(`${this.baseUrl}/users/${userId}/clients/${clientId}`);
}
getClientPreview(clientId: string): Observable<ClientPreviewResponse> {
return this.http.get<ClientPreviewResponse>(`${this.baseUrl}/preview/clients/${clientId}`);
}
getChannelPreview(channelId: string): Observable<ChannelPreview> {
return this.http.get<ChannelPreview>(`${this.baseUrl}/preview/channels/${channelId}`);
}
getKeyPreview(keyId: string): Observable<KeyTokenPreview> {
return this.http.get<KeyTokenPreview>(`${this.baseUrl}/preview/keys/${keyId}`);
}
// Channel endpoints
getChannels(userId: string, selector?: ChannelSelector): Observable<ChannelListResponse> {
let params = new HttpParams();
+117 -21
View File
@@ -1,54 +1,150 @@
import { Injectable, signal, computed } from '@angular/core';
const USER_ID_KEY = 'scn_user_id';
const ADMIN_KEY_KEY = 'scn_admin_key';
export interface Account {
userId: string;
adminKey: string;
username: string | null;
}
const ACCOUNTS_KEY = 'scn_accounts';
const ACTIVE_KEY = 'scn_active_user_id';
// Legacy single-account storage keys (migrated on first load).
const LEGACY_USER_ID_KEY = 'scn_user_id';
const LEGACY_ADMIN_KEY_KEY = 'scn_admin_key';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private userId = signal<string | null>(null);
private adminKey = signal<string | null>(null);
private _accounts = signal<Account[]>([]);
private _activeUserId = signal<string | null>(null);
isAuthenticated = computed(() => !!this.userId() && !!this.adminKey());
/** All logged-in accounts. */
accounts = this._accounts.asReadonly();
activeUserId = this._activeUserId.asReadonly();
activeAccount = computed(() => {
const id = this._activeUserId();
return this._accounts().find(a => a.userId === id) ?? null;
});
isAuthenticated = computed(() => !!this.activeAccount());
constructor() {
this.loadFromStorage();
}
private loadFromStorage(): void {
const userId = localStorage.getItem(USER_ID_KEY);
const adminKey = localStorage.getItem(ADMIN_KEY_KEY);
if (userId && adminKey) {
this.userId.set(userId);
this.adminKey.set(adminKey);
const raw = localStorage.getItem(ACCOUNTS_KEY);
if (raw) {
try {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
this._accounts.set(
parsed
.filter(a => a && a.userId && a.adminKey)
.map(a => ({ userId: a.userId, adminKey: a.adminKey, username: a.username ?? null }))
);
}
} catch {
// Ignore malformed storage; treat as logged out.
}
}
let active = localStorage.getItem(ACTIVE_KEY);
// Migrate legacy single-account storage into the multi-account format.
if (this._accounts().length === 0) {
const legacyId = localStorage.getItem(LEGACY_USER_ID_KEY);
const legacyKey = localStorage.getItem(LEGACY_ADMIN_KEY_KEY);
if (legacyId && legacyKey) {
this._accounts.set([{ userId: legacyId, adminKey: legacyKey, username: null }]);
active = legacyId;
localStorage.removeItem(LEGACY_USER_ID_KEY);
localStorage.removeItem(LEGACY_ADMIN_KEY_KEY);
this.persist(active);
}
}
// Ensure the active pointer references an existing account.
if (!active || !this._accounts().some(a => a.userId === active)) {
active = this._accounts()[0]?.userId ?? null;
}
this._activeUserId.set(active);
}
private persist(activeOverride?: string | null): void {
localStorage.setItem(ACCOUNTS_KEY, JSON.stringify(this._accounts()));
const active = activeOverride !== undefined ? activeOverride : this._activeUserId();
if (active) {
localStorage.setItem(ACTIVE_KEY, active);
} else {
localStorage.removeItem(ACTIVE_KEY);
}
}
/** Add (or update) an account and make it the active one. */
login(userId: string, adminKey: string): void {
localStorage.setItem(USER_ID_KEY, userId);
localStorage.setItem(ADMIN_KEY_KEY, adminKey);
this.userId.set(userId);
this.adminKey.set(adminKey);
if (this._accounts().some(a => a.userId === userId)) {
this._accounts.update(list =>
list.map(a => (a.userId === userId ? { ...a, adminKey } : a))
);
} else {
this._accounts.update(list => [...list, { userId, adminKey, username: null }]);
}
this._activeUserId.set(userId);
this.persist();
}
/** Log out the currently active account. */
logout(): void {
localStorage.removeItem(USER_ID_KEY);
localStorage.removeItem(ADMIN_KEY_KEY);
this.userId.set(null);
this.adminKey.set(null);
const active = this._activeUserId();
if (active) {
this.removeAccount(active);
}
}
/** Log out a specific account (active or background). */
logoutAccount(userId: string): void {
this.removeAccount(userId);
}
private removeAccount(userId: string): void {
this._accounts.update(list => list.filter(a => a.userId !== userId));
if (this._activeUserId() === userId) {
this._activeUserId.set(this._accounts()[0]?.userId ?? null);
}
this.persist();
}
/** Switch which logged-in account is active. */
switchAccount(userId: string): void {
if (!this._accounts().some(a => a.userId === userId)) return;
this._activeUserId.set(userId);
this.persist();
}
/** Cache the resolved username on the active account. */
setActiveUsername(username: string | null): void {
const active = this._activeUserId();
if (!active) return;
this._accounts.update(list =>
list.map(a => (a.userId === active ? { ...a, username } : a))
);
this.persist();
}
getUserId(): string | null {
return this.userId();
return this._activeUserId();
}
getAdminKey(): string | null {
return this.adminKey();
return this.activeAccount()?.adminKey ?? null;
}
getAuthHeader(): string | null {
const key = this.adminKey();
const key = this.getAdminKey();
return key ? `SCN ${key}` : null;
}
}
@@ -0,0 +1,41 @@
import { Injectable, inject } from '@angular/core';
import { Observable, of, catchError, map, shareReplay } from 'rxjs';
import { ApiService } from './api.service';
import { ClientPreview, UserPreview } from '../models';
export interface ResolvedClient {
clientId: string;
clientName: string | null;
userId: string;
userName: string | null;
agentModel: string;
agentVersion: string;
}
@Injectable({
providedIn: 'root'
})
export class ClientCacheService {
private apiService = inject(ApiService);
private cache = new Map<string, Observable<{client: ClientPreview, user: UserPreview} | null>>();
resolveClient(clientId: string): Observable<{client: ClientPreview, user: UserPreview} | null> {
if (!this.cache.has(clientId)) {
const request$ = this.apiService.getClientPreview(clientId).pipe(
map(response => ({
client: response.client,
user: response.user
})),
catchError(() => of(null)),
shareReplay(1)
);
this.cache.set(clientId, request$);
}
return this.cache.get(clientId)!;
}
clearCache(): void {
this.cache.clear();
}
}
@@ -137,7 +137,12 @@ export class AccountInfoComponent implements OnInit {
next: () => {
this.notification.success('Account deleted');
this.authService.logout();
this.router.navigate(['/login']);
if (this.authService.isAuthenticated()) {
// Another account is still logged in — reload into it cleanly.
window.location.assign('/');
} else {
this.router.navigate(['/login']);
}
},
error: () => {
this.deleting.set(false);
@@ -1,6 +1,6 @@
import { Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, ActivatedRoute } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzButtonModule } from 'ng-zorro-antd/button';
@@ -27,7 +27,6 @@ import { isAdminKey } from '../../../core/models';
export class LoginComponent {
private authService = inject(AuthService);
private apiService = inject(ApiService);
private router = inject(Router);
private route = inject(ActivatedRoute);
userId = '';
@@ -56,9 +55,11 @@ export class LoginComponent {
return;
}
// Login successful
// Login successful. Use a full navigation so all per-account state
// (singleton caches, component signals) is initialised for the new
// active account — important when adding a second account.
const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/messages';
this.router.navigateByUrl(returnUrl);
window.location.assign(returnUrl);
},
error: (err) => {
this.authService.logout();
@@ -3,7 +3,7 @@
<div class="loading-container">
<nz-spin nzSimple nzSize="large"></nz-spin>
</div>
} @else if (channel()) {
} @else if (channelData()) {
<div class="detail-header">
<button nz-button (click)="goBack()">
<span nz-icon nzType="arrow-left" nzTheme="outline"></span>
@@ -32,13 +32,13 @@
}
</div>
<nz-card [nzTitle]="channel()!.display_name">
<nz-card [nzTitle]="channelData()!.display_name">
<scn-metadata-grid>
<scn-metadata-value label="Channel ID">
<span class="mono">{{ channel()!.channel_id }}</span>
<span class="mono">{{ channelData()!.channel_id }}</span>
</scn-metadata-value>
<scn-metadata-value label="Internal Name">
<span class="mono">{{ channel()!.internal_name }}</span>
<span class="mono">{{ channelData()!.internal_name }}</span>
</scn-metadata-value>
<scn-metadata-value label="Status">
<nz-tag [nzColor]="getSubscriptionStatus().color">
@@ -46,29 +46,36 @@
</nz-tag>
</scn-metadata-value>
<scn-metadata-value label="Owner">
<span class="mono">{{ channel()!.owner_user_id }}</span>
@if (resolvedOwner()) {
<div class="owner-name">{{ resolvedOwner()!.displayName }}</div>
<div class="owner-id mono">{{ channelData()!.owner_user_id }}</div>
} @else {
<span class="mono">{{ channelData()!.owner_user_id }}</span>
}
</scn-metadata-value>
@if (channel()!.description_name) {
@if (channelData()!.description_name) {
<scn-metadata-value label="Description">
{{ channel()!.description_name }}
{{ channelData()!.description_name }}
</scn-metadata-value>
}
<scn-metadata-value label="Messages Sent">
{{ channel()!.messages_sent }}
{{ channelData()!.messages_sent }}
</scn-metadata-value>
<scn-metadata-value label="Last Sent">
@if (channel()!.timestamp_lastsent) {
<div class="timestamp-absolute">{{ channel()!.timestamp_lastsent | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ channel()!.timestamp_lastsent | relativeTime }}</div>
} @else {
Never
}
</scn-metadata-value>
<scn-metadata-value label="Created">
<div class="timestamp-absolute">{{ channel()!.timestamp_created | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ channel()!.timestamp_created | relativeTime }}</div>
</scn-metadata-value>
@if (isOwner() && channel()!.subscribe_key) {
@if (channel()) {
<scn-metadata-value label="Last Sent">
@if (channel()!.timestamp_lastsent) {
<div class="timestamp-absolute">{{ channel()!.timestamp_lastsent | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ channel()!.timestamp_lastsent | relativeTime }}</div>
} @else {
Never
}
</scn-metadata-value>
<scn-metadata-value label="Created">
<div class="timestamp-absolute">{{ channel()!.timestamp_created | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ channel()!.timestamp_created | relativeTime }}</div>
</scn-metadata-value>
}
@if (isOwner() && channel()?.subscribe_key) {
<scn-metadata-value label="Subscribe Key">
<div class="key-field">
<nz-input-group [nzSuffix]="subscribeKeySuffix">
@@ -109,6 +109,17 @@
overflow-y: clip;
}
.owner-name {
font-weight: 500;
color: #333;
}
.owner-id {
font-size: 11px;
color: #999;
margin-top: 2px;
}
.text-muted {
color: #999;
}
@@ -21,7 +21,7 @@ import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { SettingsService } from '../../../core/services/settings.service';
import { UserCacheService, ResolvedUser } from '../../../core/services/user-cache.service';
import { ChannelWithSubscription, Subscription, Message } from '../../../core/models';
import { ChannelWithSubscription, ChannelPreview, Subscription, Message } from '../../../core/models';
import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
import { CopyToClipboardDirective } from '../../../shared/directives/copy-to-clipboard.directive';
import { QrCodeDisplayComponent } from '../../../shared/components/qr-code-display/qr-code-display.component';
@@ -68,9 +68,11 @@ export class ChannelDetailComponent implements OnInit {
private userCacheService = inject(UserCacheService);
channel = signal<ChannelWithSubscription | null>(null);
channelPreview = signal<ChannelPreview | null>(null);
subscriptions = signal<Subscription[]>([]);
messages = signal<Message[]>([]);
userNames = signal<Map<string, ResolvedUser>>(new Map());
resolvedOwner = signal<ResolvedUser | null>(null);
loading = signal(true);
loadingSubscriptions = signal(false);
loadingMessages = signal(false);
@@ -115,14 +117,26 @@ export class ChannelDetailComponent implements OnInit {
if (!userId) return;
this.loading.set(true);
this.apiService.getChannel(userId, channelId).subscribe({
next: (channel) => {
this.channel.set(channel);
this.loading.set(false);
if (this.isOwner()) {
this.loadSubscriptions(channelId);
this.apiService.getChannelPreview(channelId).subscribe({
next: (preview) => {
this.channelPreview.set(preview);
this.resolveOwner(preview.owner_user_id);
if (preview.owner_user_id === userId) {
this.apiService.getChannel(userId, channelId).subscribe({
next: (channel) => {
this.channel.set(channel);
this.loading.set(false);
this.loadSubscriptions(channelId);
this.loadMessages(channelId);
},
error: () => {
this.loading.set(false);
}
});
} else {
this.loading.set(false);
this.loadMessages(channelId);
}
this.loadMessages(channelId);
},
error: () => {
this.loading.set(false);
@@ -148,14 +162,13 @@ export class ChannelDetailComponent implements OnInit {
}
loadMessages(channelId: string, nextPageToken?: string): void {
const userId = this.authService.getUserId();
if (!userId) return;
this.loadingMessages.set(true);
this.apiService.getChannelMessages(userId, channelId, {
this.apiService.getMessages({
channel_id: [channelId],
page_size: this.messagesPageSize,
next_page_token: nextPageToken,
trimmed: true
trimmed: true,
subscription_status: 'all'
}).subscribe({
next: (response) => {
this.messages.set(response.messages);
@@ -210,6 +223,12 @@ export class ChannelDetailComponent implements OnInit {
}
}
private resolveOwner(ownerId: string): void {
this.userCacheService.resolveUser(ownerId).subscribe(resolved => {
this.resolvedOwner.set(resolved);
});
}
private resolveUserNames(subscriptions: Subscription[]): void {
const userIds = new Set<string>();
for (const sub of subscriptions) {
@@ -232,9 +251,16 @@ export class ChannelDetailComponent implements OnInit {
}
isOwner(): boolean {
const channel = this.channel();
const userId = this.authService.getUserId();
return channel?.owner_user_id === userId;
const channel = this.channel();
if (channel) return channel.owner_user_id === userId;
const preview = this.channelPreview();
if (preview) return preview.owner_user_id === userId;
return false;
}
channelData() {
return this.channel() ?? this.channelPreview();
}
// Edit methods
@@ -290,18 +316,20 @@ export class ChannelDetailComponent implements OnInit {
}
getSubscriptionStatus(): { label: string; color: string } {
const channel = this.channel();
if (!channel) return { label: 'Unknown', color: 'default' };
const data = this.channelData();
if (!data) return { label: 'Unknown', color: 'default' };
const subscription = 'subscribe_key' in data ? data.subscription : data.subscription;
if (this.isOwner()) {
if (channel.subscription) {
if (subscription) {
return { label: 'Owned & Subscribed', color: 'green' };
}
return { label: 'Owned', color: 'blue' };
}
if (channel.subscription) {
if (channel.subscription.confirmed) {
if (subscription) {
if (subscription.confirmed) {
return { label: 'Subscribed', color: 'green' };
}
return { label: 'Pending', color: 'orange' };
@@ -377,7 +405,7 @@ export class ChannelDetailComponent implements OnInit {
}
isUserSubscribed(): boolean {
return this.channel()?.subscription !== null;
return this.channelData()?.subscription !== null && this.channelData()?.subscription !== undefined;
}
toggleSelfSubscription(): void {
@@ -50,50 +50,30 @@
</thead>
<tbody>
@for (channel of channels(); track channel.channel_id) {
<tr [class.clickable-row]="isOwned(channel)">
<tr class="clickable-row">
<td>
@if (isOwned(channel)) {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<div class="channel-name">{{ channel.display_name }}</div>
<div class="channel-id mono">{{ channel.channel_id }}</div>
</a>
} @else {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<div class="channel-name">{{ channel.display_name }}</div>
<div class="channel-id mono">{{ channel.channel_id }}</div>
}
</a>
</td>
<td>
@if (isOwned(channel)) {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<span class="mono">{{ channel.internal_name }}</span>
</a>
} @else {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<span class="mono">{{ channel.internal_name }}</span>
}
</a>
</td>
<td>
@if (isOwned(channel)) {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<div class="channel-name">{{ getOwnerDisplayName(channel.owner_user_id) }}</div>
<div class="channel-id mono">{{ channel.owner_user_id }}</div>
</a>
} @else {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<div class="channel-name">{{ getOwnerDisplayName(channel.owner_user_id) }}</div>
<div class="channel-id mono">{{ channel.owner_user_id }}</div>
}
</a>
</td>
<td>
@if (isOwned(channel)) {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<nz-tag [nzColor]="getSubscriptionStatus(channel).color">
{{ getSubscriptionStatus(channel).label }}
</nz-tag>
</a>
} @else {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<nz-tag [nzColor]="getSubscriptionStatus(channel).color">
{{ getSubscriptionStatus(channel).label }}
</nz-tag>
}
</a>
</td>
<td>
@if (isOwned(channel)) {
@@ -105,32 +85,19 @@
}
</td>
<td>
@if (isOwned(channel)) {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
{{ channel.messages_sent }}
</a>
} @else {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
{{ channel.messages_sent }}
}
</a>
</td>
<td>
@if (isOwned(channel)) {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
@if (channel.timestamp_lastsent) {
<div class="timestamp-absolute">{{ channel.timestamp_lastsent | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ channel.timestamp_lastsent | relativeTime }}</div>
} @else {
<span class="text-muted">Never</span>
}
</a>
} @else {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
@if (channel.timestamp_lastsent) {
<div class="timestamp-absolute">{{ channel.timestamp_lastsent | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ channel.timestamp_lastsent | relativeTime }}</div>
} @else {
<span class="text-muted">Never</span>
}
}
</a>
</td>
@if (expertMode()) {
<td>
@@ -3,13 +3,13 @@
<div class="loading-container">
<nz-spin nzSimple nzSize="large"></nz-spin>
</div>
} @else if (client()) {
} @else if (clientData()) {
<div class="detail-header">
<button nz-button (click)="goBack()">
<span nz-icon nzType="arrow-left" nzTheme="outline"></span>
Back to Clients
</button>
@if (expertMode()) {
@if (isOwner() && expertMode()) {
<div class="header-actions">
<button
nz-button
@@ -29,36 +29,38 @@
<div class="client-header">
<span
nz-icon
[nzType]="getClientIcon(client()!.type)"
[nzType]="getClientIcon(clientData()!.type)"
nzTheme="outline"
class="client-type-icon"
></span>
<h2 class="client-title">{{ client()!.name || 'Unnamed Client' }}</h2>
<nz-tag>{{ getClientTypeLabel(client()!.type) }}</nz-tag>
<h2 class="client-title">{{ clientData()!.name || 'Unnamed Client' }}</h2>
<nz-tag>{{ getClientTypeLabel(clientData()!.type) }}</nz-tag>
</div>
<scn-metadata-grid>
<scn-metadata-value label="Client ID">
<span class="mono">{{ client()!.client_id }}</span>
<span class="mono">{{ clientData()!.client_id }}</span>
</scn-metadata-value>
<scn-metadata-value label="Type">
<nz-tag>{{ getClientTypeLabel(client()!.type) }}</nz-tag>
<nz-tag>{{ getClientTypeLabel(clientData()!.type) }}</nz-tag>
</scn-metadata-value>
<scn-metadata-value label="Agent">
<div class="agent-info">
<span>{{ client()!.agent_model }}</span>
<span class="agent-version">v{{ client()!.agent_version }}</span>
<span>{{ clientData()!.agent_model }}</span>
<span class="agent-version">v{{ clientData()!.agent_version }}</span>
</div>
</scn-metadata-value>
<scn-metadata-value label="Created">
<div class="timestamp-absolute">{{ client()!.timestamp_created | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ client()!.timestamp_created | relativeTime }}</div>
</scn-metadata-value>
<scn-metadata-value label="FCM Token">
<span class="mono fcm-token" nz-tooltip [nzTooltipTitle]="client()!.fcm_token">
{{ client()!.fcm_token }}
</span>
<div class="timestamp-absolute">{{ clientData()!.timestamp_created | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ clientData()!.timestamp_created | relativeTime }}</div>
</scn-metadata-value>
@if (client()) {
<scn-metadata-value label="FCM Token">
<span class="mono fcm-token" nz-tooltip [nzTooltipTitle]="client()!.fcm_token">
{{ client()!.fcm_token }}
</span>
</scn-metadata-value>
}
</scn-metadata-grid>
</nz-card>
} @else {
@@ -12,7 +12,7 @@ import { ApiService } from '../../../core/services/api.service';
import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { SettingsService } from '../../../core/services/settings.service';
import { Client, ClientType, getClientTypeIcon } from '../../../core/models';
import { Client, ClientPreview, ClientType, getClientTypeIcon } from '../../../core/models';
import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
import { MetadataGridComponent, MetadataValueComponent } from '../../../shared/components/metadata-grid';
@@ -45,6 +45,7 @@ export class ClientDetailComponent implements OnInit {
private settingsService = inject(SettingsService);
client = signal<Client | null>(null);
clientPreview = signal<ClientPreview | null>(null);
loading = signal(true);
expertMode = this.settingsService.expertMode;
@@ -60,10 +61,22 @@ export class ClientDetailComponent implements OnInit {
if (!userId) return;
this.loading.set(true);
this.apiService.getClient(userId, clientId).subscribe({
next: (client) => {
this.client.set(client);
this.loading.set(false);
this.apiService.getClientPreview(clientId).subscribe({
next: (response) => {
this.clientPreview.set(response.client);
if (response.client.user_id === userId) {
this.apiService.getClient(userId, clientId).subscribe({
next: (client) => {
this.client.set(client);
this.loading.set(false);
},
error: () => {
this.loading.set(false);
}
});
} else {
this.loading.set(false);
}
},
error: () => {
this.loading.set(false);
@@ -71,6 +84,19 @@ export class ClientDetailComponent implements OnInit {
});
}
clientData() {
return this.client() ?? this.clientPreview();
}
isOwner(): boolean {
const userId = this.authService.getUserId();
const client = this.client();
if (client) return client.user_id === userId;
const preview = this.clientPreview();
if (preview) return preview.user_id === userId;
return false;
}
goBack(): void {
this.router.navigate(['/clients']);
}
@@ -3,35 +3,37 @@
<div class="loading-container">
<nz-spin nzSimple nzSize="large"></nz-spin>
</div>
} @else if (key()) {
} @else if (keyData()) {
<div class="detail-header">
<button nz-button (click)="goBack()">
<span nz-icon nzType="arrow-left" nzTheme="outline"></span>
Back to Keys
</button>
<div class="header-actions">
<button nz-button (click)="openEditModal()">
<span nz-icon nzType="edit"></span>
Edit
</button>
@if (!isCurrentKey()) {
<button
nz-button
nzDanger
nz-popconfirm
nzPopconfirmTitle="Are you sure you want to delete this key?"
(nzOnConfirm)="deleteKey()"
>
<span nz-icon nzType="delete"></span>
Delete
@if (isOwner()) {
<div class="header-actions">
<button nz-button (click)="openEditModal()">
<span nz-icon nzType="edit"></span>
Edit
</button>
}
</div>
@if (!isCurrentKey()) {
<button
nz-button
nzDanger
nz-popconfirm
nzPopconfirmTitle="Are you sure you want to delete this key?"
(nzOnConfirm)="deleteKey()"
>
<span nz-icon nzType="delete"></span>
Delete
</button>
}
</div>
}
</div>
<nz-card>
<div class="key-header">
<h2 class="key-title">{{ key()!.name }}</h2>
<h2 class="key-title">{{ keyData()!.name }}</h2>
@if (isCurrentKey()) {
<nz-tag nzColor="cyan">Current</nz-tag>
}
@@ -39,7 +41,7 @@
<scn-metadata-grid>
<scn-metadata-value label="Key ID">
<span class="mono">{{ key()!.keytoken_id }}</span>
<span class="mono">{{ keyData()!.keytoken_id }}</span>
</scn-metadata-value>
<scn-metadata-value label="Permissions">
<div class="permissions">
@@ -55,11 +57,11 @@
</div>
</scn-metadata-value>
<scn-metadata-value label="Channel Access">
@if (key()!.all_channels) {
@if (keyData()!.all_channels) {
<nz-tag nzColor="default">All Channels</nz-tag>
} @else if (key()!.channels && key()!.channels.length > 0) {
} @else if (keyData()!.channels && keyData()!.channels.length > 0) {
<div class="channel-list">
@for (channelId of key()!.channels; track channelId) {
@for (channelId of keyData()!.channels; track channelId) {
<nz-tag nzColor="orange" nz-tooltip [nzTooltipTitle]="channelId">
{{ getChannelDisplayName(channelId) }}
</nz-tag>
@@ -69,27 +71,29 @@
<span class="text-muted">No channels</span>
}
</scn-metadata-value>
<scn-metadata-value label="Messages Sent">
{{ key()!.messages_sent }}
</scn-metadata-value>
<scn-metadata-value label="Created">
<div class="timestamp-absolute">{{ key()!.timestamp_created | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ key()!.timestamp_created | relativeTime }}</div>
</scn-metadata-value>
<scn-metadata-value label="Last Used">
@if (key()!.timestamp_lastused) {
<div class="timestamp-absolute">{{ key()!.timestamp_lastused | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ key()!.timestamp_lastused | relativeTime }}</div>
} @else {
<span class="text-muted">Never</span>
}
</scn-metadata-value>
@if (key()) {
<scn-metadata-value label="Messages Sent">
{{ key()!.messages_sent }}
</scn-metadata-value>
<scn-metadata-value label="Created">
<div class="timestamp-absolute">{{ key()!.timestamp_created | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ key()!.timestamp_created | relativeTime }}</div>
</scn-metadata-value>
<scn-metadata-value label="Last Used">
@if (key()!.timestamp_lastused) {
<div class="timestamp-absolute">{{ key()!.timestamp_lastused | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ key()!.timestamp_lastused | relativeTime }}</div>
} @else {
<span class="text-muted">Never</span>
}
</scn-metadata-value>
}
<scn-metadata-value label="Owner">
@if (resolvedOwner()) {
<div class="owner-name">{{ resolvedOwner()!.displayName }}</div>
<div class="owner-id mono">{{ key()!.owner_user_id }}</div>
<div class="owner-id mono">{{ keyData()!.owner_user_id }}</div>
} @else {
<span class="mono">{{ key()!.owner_user_id }}</span>
<span class="mono">{{ keyData()!.owner_user_id }}</span>
}
</scn-metadata-value>
</scn-metadata-grid>
@@ -22,7 +22,7 @@ import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { ChannelCacheService, ResolvedChannel } from '../../../core/services/channel-cache.service';
import { UserCacheService, ResolvedUser } from '../../../core/services/user-cache.service';
import { KeyToken, parsePermissions, TokenPermission, ChannelWithSubscription, Message } from '../../../core/models';
import { KeyToken, KeyTokenPreview, parsePermissions, TokenPermission, ChannelWithSubscription, Message } from '../../../core/models';
import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
import { MetadataGridComponent, MetadataValueComponent } from '../../../shared/components/metadata-grid';
@@ -72,6 +72,7 @@ export class KeyDetailComponent implements OnInit {
private userCacheService = inject(UserCacheService);
key = signal<KeyToken | null>(null);
keyPreview = signal<KeyTokenPreview | null>(null);
currentKeyId = signal<string | null>(null);
loading = signal(true);
channelNames = signal<Map<string, ResolvedChannel>>(new Map());
@@ -105,8 +106,6 @@ export class KeyDetailComponent implements OnInit {
const keyId = this.route.snapshot.paramMap.get('id');
if (keyId) {
this.loadKey(keyId);
this.loadCurrentKey();
this.loadAvailableChannels();
}
}
@@ -115,13 +114,29 @@ export class KeyDetailComponent implements OnInit {
if (!userId) return;
this.loading.set(true);
this.apiService.getKey(userId, keyId).subscribe({
next: (key) => {
this.key.set(key);
this.loading.set(false);
this.resolveChannelNames(key);
this.resolveOwner(key.owner_user_id);
this.loadMessages(keyId);
this.apiService.getKeyPreview(keyId).subscribe({
next: (preview) => {
this.keyPreview.set(preview);
this.resolveOwner(preview.owner_user_id);
this.resolveChannelNamesFromPreview(preview);
if (preview.owner_user_id === userId) {
this.loadCurrentKey();
this.loadAvailableChannels();
this.apiService.getKey(userId, keyId).subscribe({
next: (key) => {
this.key.set(key);
this.loading.set(false);
this.resolveChannelNames(key);
this.loadMessages(keyId);
},
error: () => {
this.loading.set(false);
}
});
} else {
this.loading.set(false);
this.loadMessages(keyId);
}
},
error: () => {
this.loading.set(false);
@@ -217,6 +232,27 @@ export class KeyDetailComponent implements OnInit {
}
}
private resolveChannelNamesFromPreview(preview: KeyTokenPreview): void {
if (!preview.all_channels && preview.channels && preview.channels.length > 0) {
this.channelCacheService.resolveChannels(preview.channels).subscribe(resolved => {
this.channelNames.set(resolved);
});
}
}
keyData() {
return this.key() ?? this.keyPreview();
}
isOwner(): boolean {
const userId = this.authService.getUserId();
const key = this.key();
if (key) return key.owner_user_id === userId;
const preview = this.keyPreview();
if (preview) return preview.owner_user_id === userId;
return false;
}
goBack(): void {
this.router.navigate(['/keys']);
}
@@ -227,8 +263,8 @@ export class KeyDetailComponent implements OnInit {
}
getPermissions(): TokenPermission[] {
const key = this.key();
return key ? parsePermissions(key.permissions) : [];
const data = this.keyData();
return data ? parsePermissions(data.permissions) : [];
}
getPermissionColor(perm: TokenPermission): string {
@@ -90,18 +90,29 @@
>
<thead>
<tr>
<th>Client ID</th>
<th>Client</th>
<th>User</th>
<th>Agent</th>
<th>Status</th>
<th>Retries</th>
<th>Created</th>
<th>Finalized</th>
<th>FCM-ID</th>
</tr>
</thead>
<tbody>
@for (delivery of deliveriesTable.data; track delivery.delivery_id) {
<tr>
<td>
<span class="mono">{{ delivery.receiver_client_id }}</span>
<div class="cell-name">{{ getResolvedClient(delivery.receiver_client_id)?.client?.name ?? '-' }}</div>
<div class="cell-id mono">{{ delivery.receiver_client_id }}</div>
</td>
<td>
<div class="cell-name">{{ getResolvedClient(delivery.receiver_client_id)?.user?.username ?? '-' }}</div>
<div class="cell-id mono">{{ delivery.receiver_user_id }}</div>
</td>
<td>
{{ getResolvedClient(delivery.receiver_client_id)?.client?.agent_model ?? '-' }}
</td>
<td>
<nz-tag [nzColor]="getStatusColor(delivery.status)">
@@ -111,6 +122,21 @@
<td>{{ delivery.retry_count }}</td>
<td>{{ delivery.timestamp_created | date:'yyyy-MM-dd HH:mm:ss' }}</td>
<td>{{ delivery.timestamp_finalized ? (delivery.timestamp_finalized | date:'yyyy-MM-dd HH:mm:ss') : '-' }}</td>
<td>
@if (delivery.fcm_message_id) {
<span
nz-icon
nzType="copy"
class="action-icon"
nz-tooltip
nzTooltipTitle="Copy Message FCM-ID"
style="cursor: pointer"
[appCopyToClipboard]="delivery.fcm_message_id"
></span>
} @else {
-
}
</td>
</tr>
}
</tbody>
@@ -8,13 +8,16 @@ import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzToolTipModule } from 'ng-zorro-antd/tooltip';
import { ApiService } from '../../../core/services/api.service';
import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { SettingsService } from '../../../core/services/settings.service';
import { KeyCacheService, ResolvedKey } from '../../../core/services/key-cache.service';
import { UserCacheService, ResolvedUser } from '../../../core/services/user-cache.service';
import { Message, Delivery } from '../../../core/models';
import { ClientCacheService, ResolvedClient } from '../../../core/services/client-cache.service';
import { Message, Delivery, ClientPreview, UserPreview } from '../../../core/models';
import { CopyToClipboardDirective } from '../../../shared/directives/copy-to-clipboard.directive';
import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
import { MetadataGridComponent, MetadataValueComponent } from '../../../shared/components/metadata-grid';
@@ -31,10 +34,12 @@ import { MetadataGridComponent, MetadataValueComponent } from '../../../shared/c
NzSpinModule,
NzPopconfirmModule,
NzTableModule,
NzToolTipModule,
RouterLink,
RelativeTimePipe,
MetadataGridComponent,
MetadataValueComponent,
CopyToClipboardDirective,
],
templateUrl: './message-detail.component.html',
styleUrl: './message-detail.component.scss'
@@ -48,11 +53,13 @@ export class MessageDetailComponent implements OnInit {
private settingsService = inject(SettingsService);
private keyCacheService = inject(KeyCacheService);
private userCacheService = inject(UserCacheService);
private clientCacheService = inject(ClientCacheService);
message = signal<Message | null>(null);
resolvedKey = signal<ResolvedKey | null>(null);
resolvedChannelOwner = signal<ResolvedUser | null>(null);
deliveries = signal<Delivery[]>([]);
resolvedClients = signal<Map<string, {client: ClientPreview, user: UserPreview}>>(new Map());
loading = signal(true);
deleting = signal(false);
loadingDeliveries = signal(false);
@@ -107,6 +114,7 @@ export class MessageDetailComponent implements OnInit {
next: (response) => {
this.deliveries.set(response.deliveries);
this.loadingDeliveries.set(false);
this.resolveDeliveryClients(response.deliveries);
},
error: () => {
this.loadingDeliveries.set(false);
@@ -114,6 +122,27 @@ export class MessageDetailComponent implements OnInit {
});
}
private resolveDeliveryClients(deliveries: Delivery[]): void {
const uniqueClientIds = [...new Set(deliveries.map(d => d.receiver_client_id))];
for (const clientId of uniqueClientIds) {
this.clientCacheService.resolveClient(clientId).subscribe({
next: (resolved) => {
if (resolved) {
this.resolvedClients.update(map => {
const newMap = new Map(map);
newMap.set(clientId, resolved);
return newMap;
});
}
}
});
}
}
getResolvedClient(clientId: string): {client: ClientPreview, user: UserPreview} | undefined {
return this.resolvedClients().get(clientId);
}
private resolveKey(keyId: string): void {
this.keyCacheService.resolveKey(keyId).subscribe({
next: (resolved) => this.resolvedKey.set(resolved)
@@ -56,24 +56,25 @@
</span>
</div>
<div class="header-right">
<div class="expert-mode-toggle">
<nz-switch
[ngModel]="expertMode()"
(ngModelChange)="settingsService.setExpertMode($event)"
nzSize="small"
></nz-switch>
<span class="expert-mode-label">Expert</span>
<div
class="account-trigger"
nz-dropdown
nzTrigger="click"
[nzClickHide]="false"
nzPlacement="bottomRight"
[nzDropdownMenu]="accountMenu"
>
<div class="user-info">
@if (username()) {
<span class="username">{{ username() }}</span>
}
<span class="user-id mono">{{ userId }}</span>
@if (currentKey()) {
<span class="key-id mono">{{ currentKey()!.keytoken_id }}</span>
}
</div>
<span nz-icon nzType="down" class="account-caret"></span>
</div>
<div class="user-info">
<span class="user-id mono">{{ userId }}</span>
@if (currentKey()) {
<span class="key-id mono">{{ currentKey()!.keytoken_id }}</span>
}
</div>
<button nz-button nzType="text" nzDanger (click)="logout()">
<span nz-icon nzType="logout"></span>
Logout
</button>
</div>
</nz-header>
<nz-content class="content-area">
@@ -81,3 +82,65 @@
</nz-content>
</nz-layout>
</nz-layout>
<nz-dropdown-menu #accountMenu="nzDropdownMenu">
<div class="account-dropdown">
<!-- Settings -->
<div class="dropdown-section">
<div class="settings-row">
<span class="settings-label">
<span nz-icon nzType="setting"></span>
Expert mode
</span>
<nz-switch
[ngModel]="expertMode()"
(ngModelChange)="settingsService.setExpertMode($event)"
nzSize="small"
></nz-switch>
</div>
</div>
<div class="dropdown-divider"></div>
<!-- Accounts -->
<div class="dropdown-section accounts-section">
@for (acc of accounts(); track acc.userId) {
<div
class="account-item"
[class.active]="acc.userId === userId"
(click)="switchAccount(acc.userId)"
>
<span nz-icon nzType="user" class="account-avatar"></span>
<div class="account-meta">
<span class="account-name">{{ acc.username || acc.userId }}</span>
<span class="account-sub mono">{{ acc.userId }}</span>
</div>
@if (acc.userId === userId) {
<span nz-icon nzType="check" class="account-check"></span>
}
<button
nz-button
nzType="text"
nzSize="small"
nzDanger
class="account-logout"
title="Logout"
(click)="logoutAccount(acc.userId, $event)"
>
<span nz-icon nzType="logout"></span>
</button>
</div>
}
</div>
<div class="dropdown-divider"></div>
<!-- Add account -->
<div class="dropdown-section">
<button nz-button nzType="text" class="add-account-btn" (click)="addAccount()">
<span nz-icon nzType="user-add"></span>
Login with another account
</button>
</div>
</div>
</nz-dropdown-menu>
@@ -51,17 +51,6 @@
align-items: center;
}
.expert-mode-toggle {
display: flex;
align-items: center;
gap: 8px;
.expert-mode-label {
font-size: 13px;
color: #666;
}
}
.header-trigger {
font-size: 18px;
cursor: pointer;
@@ -79,11 +68,49 @@
gap: 16px;
}
// --- Account switcher trigger (in header) ---
.account-trigger {
display: flex;
align-items: center;
gap: 10px;
cursor: pointer;
padding: 6px 10px;
border-radius: 8px;
max-width: 260px;
transition: background 0.2s;
&:hover {
background: rgba(0, 0, 0, 0.04);
}
.account-caret {
font-size: 11px;
color: #999;
flex-shrink: 0;
}
}
.user-info {
display: flex;
flex-direction: column;
align-items: flex-end;
line-height: 1.3;
min-width: 0;
.username,
.user-id,
.key-id {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.username {
color: #333;
font-size: 13px;
font-weight: 600;
}
.user-id {
color: #666;
@@ -96,6 +123,120 @@
}
}
// --- Account switcher dropdown panel ---
.account-dropdown {
background: #fff;
border-radius: 8px;
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.14);
padding: 6px;
min-width: 260px;
max-width: calc(100vw - 24px);
}
.dropdown-section {
display: flex;
flex-direction: column;
}
.dropdown-divider {
height: 1px;
background: #f0f0f0;
margin: 6px 4px;
}
.settings-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 8px 10px;
.settings-label {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
color: #333;
}
}
.accounts-section {
max-height: 40vh;
overflow-y: auto;
}
.account-item {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 10px;
border-radius: 6px;
cursor: pointer;
transition: background 0.2s;
&:hover {
background: rgba(0, 0, 0, 0.04);
}
&.active {
background: #e6f4ff;
&:hover {
background: #d6ecff;
}
}
.account-avatar {
font-size: 18px;
color: #888;
flex-shrink: 0;
}
.account-meta {
display: flex;
flex-direction: column;
line-height: 1.3;
min-width: 0;
flex: 1;
.account-name {
font-size: 14px;
font-weight: 600;
color: #333;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.account-sub {
font-size: 12px;
color: #999;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.account-check {
color: #1890ff;
flex-shrink: 0;
}
.account-logout {
flex-shrink: 0;
}
}
.add-account-btn {
width: 100%;
display: flex;
align-items: center;
justify-content: flex-start;
gap: 8px;
padding: 8px 10px;
height: auto;
}
.content-area {
margin-left: 240px;
transition: margin-left 0.2s;
@@ -116,3 +257,25 @@ nz-layout:has(.ant-layout-sider-collapsed) .content-area {
margin-left: 80px;
}
}
// --- Mobile ---
@media (max-width: 600px) {
.app-header {
padding: 0 12px;
}
.header-right {
gap: 8px;
}
.account-trigger {
max-width: 62vw;
gap: 6px;
padding: 6px;
// Keep the trigger to one identifying line on small screens.
.user-info .key-id {
display: none;
}
}
}
@@ -39,11 +39,14 @@ export class MainLayoutComponent implements OnInit {
isCollapsed = signal(false);
userId = this.authService.getUserId();
accounts = this.authService.accounts;
currentKey = signal<KeyToken | null>(null);
username = signal<string | null>(null);
expertMode = this.settingsService.expertMode;
ngOnInit(): void {
this.loadCurrentKey();
this.loadUser();
}
private loadCurrentKey(): void {
@@ -55,12 +58,44 @@ export class MainLayoutComponent implements OnInit {
});
}
private loadUser(): void {
const userId = this.userId;
if (!userId) return;
this.apiService.getUser(userId).subscribe({
next: (user) => {
this.username.set(user.username);
// Cache the resolved name so the account switcher can label it.
this.authService.setActiveUsername(user.username);
}
});
}
toggleCollapsed(): void {
this.isCollapsed.update(v => !v);
}
logout(): void {
this.authService.logout();
switchAccount(userId: string): void {
if (userId === this.userId) return;
this.authService.switchAccount(userId);
// Full reload so all per-account state (caches, component signals) resets cleanly.
window.location.assign('/');
}
logoutAccount(userId: string, event: Event): void {
event.stopPropagation();
const wasActive = userId === this.authService.getUserId();
this.authService.logoutAccount(userId);
if (!this.authService.isAuthenticated()) {
this.router.navigate(['/login']);
} else if (wasActive) {
window.location.assign('/');
}
// Otherwise a background account was removed; the accounts() signal updates the list.
}
addAccount(): void {
this.router.navigate(['/login']);
}
}