Compare commits

...
32 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
Mikescher 55a91956ce Implement /shoutrrr endpoint
Build Docker and Deploy / Build Docker Container (push) Successful in 1m20s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 9m51s
Build Docker and Deploy / Deploy to Server (push) Successful in 27s
2025-12-18 11:36:15 +01:00
Mikescher 202603d16c More webapp changes+fixes
Build Docker and Deploy / Build Docker Container (push) Successful in 1m45s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 9m31s
Build Docker and Deploy / Deploy to Server (push) Successful in 22s
2025-12-09 16:45:51 +01:00
Mikescher c81143ecdc More webapp changes+fixes
Build Docker and Deploy / Build Docker Container (push) Successful in 1m0s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 9m18s
Build Docker and Deploy / Deploy to Server (push) Successful in 22s
2025-12-07 04:21:11 +01:00
Mikescher 2b7950f5dc More webapp changes+fixes
Build Docker and Deploy / Build Docker Container (push) Successful in 1m41s
Build Docker and Deploy / Run Unit-Tests (push) Successful in 9m31s
Build Docker and Deploy / Deploy to Server (push) Successful in 18s
2025-12-05 21:39:32 +01:00
Mikescher c554479604 Implement /deliveries route 2025-12-05 16:59:56 +01:00
Mikescher 8e7a540c97 More webapp changes+fixes 2025-12-05 16:58:30 +01:00
Mikescher c66cd0568f Merge branch 'test/remove_userid_param' 2025-12-05 14:30:55 +01:00
Mikescher 0800d25b30 Remove required user_id param when sending messages 2025-12-05 14:30:44 +01:00
Mikescher 6d180aea38 Remove delete-channel from webapp 2025-12-04 09:16:47 +01:00
Mikescher 3c45191d11 fix broken links on non-owned channels
Build Docker and Deploy / Build Docker Container (push) Successful in 1m7s
Build Docker and Deploy / Run Unit-Tests (push) Failing after 10m56s
Build Docker and Deploy / Deploy to Server (push) Has been skipped
2025-12-03 22:38:24 +01:00
130 changed files with 18911 additions and 14821 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,
);
}
+24 -3
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,13 +69,15 @@ void main() async {
print('[INIT] Request Notification permissions...');
await FirebaseMessaging.instance.requestPermission(provisional: true);
FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) {
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) {
})
.onError((dynamic err) {
ApplicationLog.error('Failed to listen to token refresh events: ' + (err?.toString() ?? ''));
});
@@ -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,6 +69,11 @@ 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: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: InkWell(
onTap: () {
if (widget.mode == ChannelListItemMode.Messages) {
@@ -112,8 +117,13 @@ class _ChannelListItemState extends State<ChannelListItem> {
],
),
),
SizedBox(width: 4),
],
),
),
),
),
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));
@@ -122,14 +132,13 @@ class _ChannelListItemState extends State<ChannelListItem> {
}
},
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),
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,6 +31,11 @@ class KeyTokenListItem extends StatelessWidget {
margin: EdgeInsets.fromLTRB(0, 4, 0, 4),
shape: BeveledRectangleBorder(borderRadius: BorderRadius.circular(0)),
color: Theme.of(context).cardTheme.color,
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: InkWell(
onTap: () {
Navi.push(context, () => KeyTokenViewPage(keytokenID: item.keytokenID, preloadedData: item, needsReload: needsReload));
@@ -75,20 +80,24 @@ class KeyTokenListItem extends StatelessWidget {
],
),
),
SizedBox(width: 4),
],
),
),
),
),
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.all(8),
child: Icon(FontAwesomeIcons.solidEnvelopes, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(128), size: 24),
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,9 +28,14 @@ class SenderListItem extends StatelessWidget {
margin: EdgeInsets.fromLTRB(0, 4, 0, 4),
shape: BeveledRectangleBorder(borderRadius: BorderRadius.circular(0)),
color: Theme.of(context).cardTheme.color,
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),
@@ -68,20 +73,24 @@ class SenderListItem extends StatelessWidget {
],
),
),
SizedBox(width: 4),
],
),
),
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
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),
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
+67 -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 {
@@ -271,6 +277,65 @@ func (h APIHandler) GetMessage(pctx ginext.PreContext) ginext.HTTPResponse {
})
}
// ListMessageDeliveries swaggerdoc
//
// @Summary List deliveries for a message
// @Description The user must own the channel and request the resource with the ADMIN Key
// @ID api-messages-deliveries
// @Tags API-v2
//
// @Param mid path string true "MessageID"
//
// @Success 200 {object} handler.ListMessageDeliveries.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 "message not found"
// @Failure 500 {object} ginresp.apiError "internal server error"
//
// @Router /api/v2/messages/{mid}/deliveries [GET]
func (h APIHandler) ListMessageDeliveries(pctx ginext.PreContext) ginext.HTTPResponse {
type uri struct {
MessageID models.MessageID `uri:"mid" binding:"entityid"`
}
type response struct {
Deliveries []models.Delivery `json:"deliveries"`
}
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
}
msg, err := h.database.GetMessage(ctx, u.MessageID, false)
if errors.Is(err, sql.ErrNoRows) {
return ginresp.APIError(g, 404, apierr.MESSAGE_NOT_FOUND, "message not found", err)
}
if err != nil {
return ginresp.APIError(g, 500, apierr.DATABASE_ERROR, "Failed to query message", err)
}
// User must own the channel and have admin key
if permResp := ctx.CheckPermissionUserAdmin(msg.ChannelOwnerUserID); permResp != nil {
return *permResp
}
deliveries, err := h.database.ListDeliveriesOfMessage(ctx, msg.MessageID)
if err != nil {
return ginresp.APIError(g, 500, apierr.DATABASE_ERROR, "Failed to query deliveries", err)
}
return finishSuccess(ginext.JSON(http.StatusOK, response{Deliveries: deliveries}))
})
}
// DeleteMessage swaggerdoc
//
// @Summary Delete a single message
+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)
}
+12 -11
View File
@@ -1,6 +1,11 @@
package handler
import (
"database/sql"
"errors"
"fmt"
"net/http"
"blackforestbytes.com/simplecloudnotifier/api/apierr"
hl "blackforestbytes.com/simplecloudnotifier/api/apihighlight"
"blackforestbytes.com/simplecloudnotifier/api/ginresp"
@@ -8,13 +13,9 @@ import (
primarydb "blackforestbytes.com/simplecloudnotifier/db/impl/primary"
"blackforestbytes.com/simplecloudnotifier/logic"
"blackforestbytes.com/simplecloudnotifier/models"
"database/sql"
"errors"
"fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/dataext"
"git.blackforestbytes.com/BlackForestBytes/goext/ginext"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"net/http"
)
type CompatHandler struct {
@@ -90,7 +91,7 @@ func (h CompatHandler) SendMessage(pctx ginext.PreContext) ginext.HTTPResponse {
return ginresp.SendAPIError(g, 400, apierr.USER_NOT_FOUND, hl.USER_ID, "User not found (compat)", nil)
}
okResp, errResp := h.app.SendMessage(g, ctx, langext.Ptr(models.UserID(*newid)), data.UserKey, nil, data.Title, data.Content, data.Priority, data.UserMessageID, data.SendTimestamp, nil)
okResp, errResp := h.app.SendMessage(g, ctx, data.UserKey, nil, data.Title, data.Content, data.Priority, data.UserMessageID, data.SendTimestamp, nil)
if errResp != nil {
return *errResp
} else {
@@ -304,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")
}
@@ -416,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")
}
@@ -522,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")
}
@@ -643,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")
}
@@ -777,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")
}
@@ -900,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")
}
+65 -8
View File
@@ -1,16 +1,17 @@
package handler
import (
"fmt"
"net/http"
"time"
"blackforestbytes.com/simplecloudnotifier/api/apierr"
"blackforestbytes.com/simplecloudnotifier/api/ginresp"
primarydb "blackforestbytes.com/simplecloudnotifier/db/impl/primary"
"blackforestbytes.com/simplecloudnotifier/logic"
"blackforestbytes.com/simplecloudnotifier/models"
"fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/ginext"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"net/http"
"time"
)
type ExternalHandler struct {
@@ -27,8 +28,10 @@ func NewExternalHandler(app *logic.Application) ExternalHandler {
// UptimeKuma swaggerdoc
//
// @Summary Send a new message
// @Description All parameter can be set via query-parameter or the json body. Only UserID, UserKey and Title are required
// @Summary Send a new message (uses uptime-kuma notification schema)
// @Description Set necessary parameter via query (key, channel etc.), title+message are build from uptime-kuma payload
// @Description You can specify different channels/priorities for [up] and [down] notifications
//
// @Tags External
//
// @Param query_data query handler.UptimeKuma.query false " "
@@ -36,14 +39,13 @@ func NewExternalHandler(app *logic.Application) ExternalHandler {
//
// @Success 200 {object} handler.UptimeKuma.response
// @Failure 400 {object} ginresp.apiError
// @Failure 401 {object} ginresp.apiError "The user_id was not found or the user_key is wrong"
// @Failure 401 {object} ginresp.apiError "The user_key is wrong"
// @Failure 403 {object} ginresp.apiError "The user has exceeded its daily quota - wait 24 hours or upgrade your account"
// @Failure 500 {object} ginresp.apiError "An internal server error occurred - try again later"
//
// @Router /external/v1/uptime-kuma [POST]
func (h ExternalHandler) UptimeKuma(pctx ginext.PreContext) ginext.HTTPResponse {
type query struct {
UserID *models.UserID `form:"user_id" example:"7725"`
KeyToken *string `form:"key" example:"P3TNH8mvv14fm"`
Channel *string `form:"channel"`
ChannelUp *string `form:"channel_up"`
@@ -125,7 +127,62 @@ func (h ExternalHandler) UptimeKuma(pctx ginext.PreContext) ginext.HTTPResponse
priority = q.PriorityDown
}
okResp, errResp := h.app.SendMessage(g, ctx, q.UserID, q.KeyToken, channel, &title, &content, priority, nil, timestamp, q.SenderName)
okResp, errResp := h.app.SendMessage(g, ctx, q.KeyToken, channel, &title, &content, priority, nil, timestamp, q.SenderName)
if errResp != nil {
return *errResp
}
return finishSuccess(ginext.JSON(http.StatusOK, response{
MessageID: okResp.Message.MessageID,
}))
})
}
// Shoutrrr swaggerdoc
//
// @Summary Send a new message (uses shoutrrr generic:// format=json schema)
// @Description Set necessary parameter via query (key, channel etc.), title+message are set via the shoutrrr payload
// @Description Use the shoutrrr format `generic://{{url}}?template=json`
//
// @Tags External
//
// @Param query_data query handler.Shoutrrr.query false " "
// @Param post_body body handler.Shoutrrr.body false " "
//
// @Success 200 {object} handler.Shoutrrr.response
// @Failure 400 {object} ginresp.apiError
// @Failure 401 {object} ginresp.apiError "The user_key is wrong"
// @Failure 403 {object} ginresp.apiError "The user has exceeded its daily quota - wait 24 hours or upgrade your account"
// @Failure 500 {object} ginresp.apiError "An internal server error occurred - try again later"
//
// @Router /external/v1/uptime-kuma [POST]
func (h ExternalHandler) Shoutrrr(pctx ginext.PreContext) ginext.HTTPResponse {
type query struct {
KeyToken *string `form:"key" example:"P3TNH8mvv14fm"`
Channel *string `form:"channel"`
Priority *int `form:"priority"`
SenderName *string `form:"senderName"`
}
type body struct {
Title string `json:"title"`
Message string `json:"message"`
}
type response struct {
MessageID models.MessageID `json:"message_id"`
}
var b body
var q query
ctx, g, errResp := pctx.Query(&q).Body(&b).Start()
if errResp != nil {
return *errResp
}
defer ctx.Cancel()
return h.app.DoRequest(ctx, g, models.TLockReadWrite, func(ctx *logic.AppContext, finishSuccess func(r ginext.HTTPResponse) ginext.HTTPResponse) ginext.HTTPResponse {
okResp, errResp := h.app.SendMessage(g, ctx, q.KeyToken, q.Channel, &b.Title, &b.Message, q.Priority, nil, nil, q.SenderName)
if errResp != nil {
return *errResp
}
+4 -4
View File
@@ -1,6 +1,8 @@
package handler
import (
"net/http"
"blackforestbytes.com/simplecloudnotifier/api/apierr"
primarydb "blackforestbytes.com/simplecloudnotifier/db/impl/primary"
"blackforestbytes.com/simplecloudnotifier/logic"
@@ -8,7 +10,6 @@ import (
"git.blackforestbytes.com/BlackForestBytes/goext/dataext"
"git.blackforestbytes.com/BlackForestBytes/goext/ginext"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"net/http"
)
type SendMessageResponse struct {
@@ -42,7 +43,7 @@ func NewMessageHandler(app *logic.Application) MessageHandler {
//
// @Success 200 {object} handler.SendMessage.response
// @Failure 400 {object} ginresp.apiError
// @Failure 401 {object} ginresp.apiError "The user_id was not found or the user_key is wrong"
// @Failure 401 {object} ginresp.apiError "The user_key is wrong"
// @Failure 403 {object} ginresp.apiError "The user has exceeded its daily quota - wait 24 hours or upgrade your account"
// @Failure 500 {object} ginresp.apiError "An internal server error occurred - try again later"
//
@@ -50,7 +51,6 @@ func NewMessageHandler(app *logic.Application) MessageHandler {
// @Router /send [POST]
func (h MessageHandler) SendMessage(pctx ginext.PreContext) ginext.HTTPResponse {
type combined struct {
UserID *models.UserID `json:"user_id" form:"user_id" example:"7725" `
KeyToken *string `json:"key" form:"key" example:"P3TNH8mvv14fm" `
Channel *string `json:"channel" form:"channel" example:"test" `
Title *string `json:"title" form:"title" example:"Hello World" `
@@ -88,7 +88,7 @@ func (h MessageHandler) SendMessage(pctx ginext.PreContext) ginext.HTTPResponse
// query has highest prio, then form, then json
data := dataext.ObjectMerge(dataext.ObjectMerge(b, f), q)
okResp, errResp := h.app.SendMessage(g, ctx, data.UserID, data.KeyToken, data.Channel, data.Title, data.Content, data.Priority, data.UserMessageID, data.SendTimestamp, data.SenderName)
okResp, errResp := h.app.SendMessage(g, ctx, data.KeyToken, data.Channel, data.Title, data.Content, data.Priority, data.UserMessageID, data.SendTimestamp, data.SenderName)
if errResp != nil {
return *errResp
} else {
+3
View File
@@ -164,12 +164,14 @@ func (r *Router) Init(e *ginext.GinWrapper) error {
apiv2.GET("/messages").Handle(r.apiHandler.ListMessages)
apiv2.GET("/messages/:mid").Handle(r.apiHandler.GetMessage)
apiv2.DELETE("/messages/:mid").Handle(r.apiHandler.DeleteMessage)
apiv2.GET("/messages/:mid/deliveries").Handle(r.apiHandler.ListMessageDeliveries)
apiv2.GET("/sender-names").Handle(r.apiHandler.ListSenderNames)
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) ================
@@ -181,6 +183,7 @@ func (r *Router) Init(e *ginext.GinWrapper) error {
sendAPI.POST("/send.php").Handle(r.compatHandler.SendMessage)
sendAPI.POST("/external/v1/uptime-kuma").Handle(r.externalHandler.UptimeKuma)
sendAPI.POST("/external/v1/shoutrrr").Handle(r.externalHandler.Shoutrrr)
}
+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 {
+11 -1
View File
@@ -1,12 +1,13 @@
package primary
import (
"time"
scn "blackforestbytes.com/simplecloudnotifier"
"blackforestbytes.com/simplecloudnotifier/db"
"blackforestbytes.com/simplecloudnotifier/models"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"git.blackforestbytes.com/BlackForestBytes/goext/sq"
"time"
)
func (db *Database) CreateRetryDelivery(ctx db.TxContext, client models.Client, msg models.Message) (models.Delivery, error) {
@@ -182,3 +183,12 @@ func (db *Database) DeleteDeliveriesOfChannel(ctx db.TxContext, channelid models
return nil
}
func (db *Database) ListDeliveriesOfMessage(ctx db.TxContext, messageID models.MessageID) ([]models.Delivery, error) {
tx, err := ctx.GetOrCreateTransaction(db)
if err != nil {
return nil, err
}
return sq.QueryAll[models.Delivery](ctx, tx, "SELECT * FROM deliveries WHERE message_id = :mid AND deleted=0 ORDER BY timestamp_created ASC", sq.PP{"mid": messageID}, sq.SModeExtended, sq.Safe)
}
+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
+11 -1
View File
@@ -1,12 +1,13 @@
package primary
import (
"time"
scn "blackforestbytes.com/simplecloudnotifier"
"blackforestbytes.com/simplecloudnotifier/db"
"blackforestbytes.com/simplecloudnotifier/models"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"git.blackforestbytes.com/BlackForestBytes/goext/sq"
"time"
)
func (db *Database) CreateUser(ctx db.TxContext, protoken *string, username *string) (models.User, error) {
@@ -63,6 +64,15 @@ func (db *Database) GetUser(ctx db.TxContext, userid models.UserID) (models.User
return sq.QuerySingle[models.User](ctx, tx, "SELECT * FROM users WHERE user_id = :uid AND deleted=0 LIMIT 1", sq.PP{"uid": userid}, sq.SModeExtended, sq.Safe)
}
func (db *Database) GetUserByKey(ctx db.TxContext, key string) (models.User, error) {
tx, err := ctx.GetOrCreateTransaction(db)
if err != nil {
return models.User{}, err
}
return sq.QuerySingle[models.User](ctx, tx, "SELECT * FROM users WHERE EXISTS(SELECT keytokens.keytoken_id FROM keytokens WHERE keytokens.token = :tok AND users.user_id = keytokens.owner_user_id AND keytokens.deleted=0) AND users.deleted=0 LIMIT 1", sq.PP{"tok": key}, sq.SModeExtended, sq.Safe)
}
func (db *Database) GetUserOpt(ctx db.TxContext, userid models.UserID) (*models.User, error) {
tx, err := ctx.GetOrCreateTransaction(db)
if err != nil {
+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
}
+12 -14
View File
@@ -1,21 +1,22 @@
package logic
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
"blackforestbytes.com/simplecloudnotifier/api/apierr"
hl "blackforestbytes.com/simplecloudnotifier/api/apihighlight"
"blackforestbytes.com/simplecloudnotifier/api/ginresp"
"blackforestbytes.com/simplecloudnotifier/models"
"database/sql"
"errors"
"fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/ginext"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"git.blackforestbytes.com/BlackForestBytes/goext/mathext"
"git.blackforestbytes.com/BlackForestBytes/goext/timeext"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
"strings"
"time"
)
type SendMessageResponse struct {
@@ -25,7 +26,7 @@ type SendMessageResponse struct {
CompatMessageID int64
}
func (app *Application) SendMessage(g *gin.Context, ctx *AppContext, UserID *models.UserID, Key *string, Channel *string, Title *string, Content *string, Priority *int, UserMessageID *string, SendTimestamp *float64, SenderName *string) (*SendMessageResponse, *ginext.HTTPResponse) {
func (app *Application) SendMessage(g *gin.Context, ctx *AppContext, Key *string, Channel *string, Title *string, Content *string, Priority *int, UserMessageID *string, SendTimestamp *float64, SenderName *string) (*SendMessageResponse, *ginext.HTTPResponse) {
if Title != nil {
Title = langext.Ptr(strings.TrimSpace(*Title))
}
@@ -33,9 +34,6 @@ func (app *Application) SendMessage(g *gin.Context, ctx *AppContext, UserID *mod
UserMessageID = langext.Ptr(strings.TrimSpace(*UserMessageID))
}
if UserID == nil {
return nil, langext.Ptr(ginresp.SendAPIError(g, 400, apierr.MISSING_UID, hl.USER_ID, "Missing parameter [[user_id]]", nil))
}
if Key == nil {
return nil, langext.Ptr(ginresp.SendAPIError(g, 400, apierr.MISSING_TOK, hl.USER_KEY, "Missing parameter [[key]]", nil))
}
@@ -49,9 +47,9 @@ func (app *Application) SendMessage(g *gin.Context, ctx *AppContext, UserID *mod
return nil, langext.Ptr(ginresp.SendAPIError(g, 400, apierr.NO_TITLE, hl.TITLE, "No title specified", nil))
}
user, err := app.Database.Primary.GetUser(ctx, *UserID)
user, err := app.Database.Primary.GetUserByKey(ctx, *Key)
if errors.Is(err, sql.ErrNoRows) {
return nil, langext.Ptr(ginresp.SendAPIError(g, 400, apierr.USER_NOT_FOUND, hl.USER_ID, "User not found", err))
return nil, langext.Ptr(ginresp.SendAPIError(g, 401, apierr.USER_AUTH_FAILED, hl.USER_KEY, "Key not found or not valid", err))
}
if err != nil {
return nil, langext.Ptr(ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, hl.NONE, "Failed to query user", err))
@@ -126,7 +124,7 @@ func (app *Application) SendMessage(g *gin.Context, ctx *AppContext, UserID *mod
return nil, langext.Ptr(ginresp.SendAPIError(g, 403, apierr.QUOTA_REACHED, hl.NONE, fmt.Sprintf("Daily quota reached (%d)", user.QuotaPerDay()), nil))
}
channel, err := app.GetOrCreateChannel(ctx, *UserID, channelDisplayName, channelInternalName)
channel, err := app.GetOrCreateChannel(ctx, user.UserID, channelDisplayName, channelInternalName)
if err != nil {
return nil, langext.Ptr(ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, hl.NONE, "Failed to query/create (owned) channel", err))
}
@@ -145,7 +143,7 @@ func (app *Application) SendMessage(g *gin.Context, ctx *AppContext, UserID *mod
clientIP := g.ClientIP()
msg, err := app.Database.Primary.CreateMessage(ctx, *UserID, channel, sendTimestamp, *Title, Content, priority, UserMessageID, clientIP, SenderName, keytok.KeyTokenID)
msg, err := app.Database.Primary.CreateMessage(ctx, user.UserID, channel, sendTimestamp, *Title, Content, priority, UserMessageID, clientIP, SenderName, keytok.KeyTokenID)
if err != nil {
return nil, langext.Ptr(ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, hl.NONE, "Failed to create message in db", err))
}
@@ -176,7 +174,7 @@ func (app *Application) SendMessage(g *gin.Context, ctx *AppContext, UserID *mod
return nil, langext.Ptr(ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, hl.NONE, "Failed to inc token msg-counter", err))
}
log.Info().Msg(fmt.Sprintf("Sending new notification %s for user %s (to %d active subscriptions)", msg.MessageID, UserID, len(activeSubscriptions)))
log.Info().Msg(fmt.Sprintf("Sending new notification %s for user %s (to %d active subscriptions)", msg.MessageID, user.UserID, len(activeSubscriptions)))
for _, sub := range activeSubscriptions {
clients, err := app.Database.Primary.ListClients(ctx, sub.SubscriberUserID)
+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{
-5
View File
@@ -1143,7 +1143,6 @@ func TestChannelMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1001, 1),
})
@@ -1172,7 +1171,6 @@ func TestChannelMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1002, 1),
})
@@ -1180,19 +1178,16 @@ func TestChannelMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"channel": "Chan1",
"title": tt.ShortLipsum(1003, 1),
})
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"channel": "Chan2",
"title": tt.ShortLipsum(1004, 1),
})
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"channel": "Chan2",
"title": tt.ShortLipsum(1005, 1),
})
+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"])
}
-15
View File
@@ -126,7 +126,6 @@ func TestTokenKeys(t *testing.T) {
msg1s := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": key7.Token,
"user_id": data.UID,
"channel": "testchan1",
"title": "HelloWorld_001",
})
@@ -137,14 +136,12 @@ func TestTokenKeys(t *testing.T) {
tt.RequestPostShouldFail(t, baseUrl, "/", gin.H{
"key": key7.Token,
"user_id": data.UID,
"channel": "testchan2",
"title": "HelloWorld_001",
}, 401, apierr.USER_AUTH_FAILED) // wrong channel
tt.RequestPostShouldFail(t, baseUrl, "/", gin.H{
"key": key7.Token,
"user_id": data.UID,
"title": "HelloWorld_001",
}, 401, apierr.USER_AUTH_FAILED) // no channel (=main)
@@ -161,7 +158,6 @@ func TestTokenKeys(t *testing.T) {
tt.RequestPostShouldFail(t, baseUrl, "/", gin.H{
"key": key8.Token,
"user_id": data.UID,
"title": "HelloWorld_001",
}, 401, apierr.USER_AUTH_FAILED) // no send perm
@@ -470,14 +466,12 @@ func TestTokenKeysPermissions(t *testing.T) {
tt.RequestPostShouldFail(t, baseUrl, "/", gin.H{
"key": key7.Token,
"user_id": data.UID,
"channel": "testchan2",
"title": "HelloWorld_001",
}, 401, apierr.USER_AUTH_FAILED) // wrong channel
tt.RequestPostShouldFail(t, baseUrl, "/", gin.H{
"key": key7.Token,
"user_id": data.UID,
"title": "HelloWorld_001",
}, 401, apierr.USER_AUTH_FAILED) // no channel (=main)
@@ -494,7 +488,6 @@ func TestTokenKeysPermissions(t *testing.T) {
tt.RequestPostShouldFail(t, baseUrl, "/", gin.H{
"key": key8.Token,
"user_id": data.UID,
"title": "HelloWorld_001",
}, 401, apierr.USER_AUTH_FAILED) // no send perm
@@ -551,7 +544,6 @@ func TestTokenKeysMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1001, 1),
})
@@ -559,7 +551,6 @@ func TestTokenKeysMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1002, 1),
})
@@ -567,7 +558,6 @@ func TestTokenKeysMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": tt.ShortLipsum(1002, 1),
})
@@ -575,19 +565,16 @@ func TestTokenKeysMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"channel": "Chan1",
"title": tt.ShortLipsum(1003, 1),
})
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"channel": "Chan2",
"title": tt.ShortLipsum(1004, 1),
})
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"channel": "Chan2",
"title": tt.ShortLipsum(1005, 1),
})
@@ -597,7 +584,6 @@ func TestTokenKeysMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"channel": "Chan2",
"title": tt.ShortLipsum(1004, 1),
})
@@ -606,7 +592,6 @@ func TestTokenKeysMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1002, 1),
})
+11 -2
View File
@@ -2,11 +2,13 @@ package test
import (
"database/sql"
"os"
"testing"
tt "blackforestbytes.com/simplecloudnotifier/test/util"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/glebarez/go-sqlite"
"os"
"testing"
)
func TestMain(m *testing.M) {
@@ -20,3 +22,10 @@ func TestMain(m *testing.M) {
os.Exit(m.Run())
}
func TestInitFactory(t *testing.T) {
ws, _, stop := tt.StartSimpleWebserver(t)
defer stop()
tt.InitDefaultData(t, ws)
}
+115 -13
View File
@@ -418,13 +418,11 @@ func TestDeleteMessage(t *testing.T) {
"fcm_token": "DUMMY_FCM",
})
uid := r0["user_id"].(string)
sendtok := r0["send_key"].(string)
admintok := r0["admin_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": "Message_1",
})
@@ -446,13 +444,11 @@ func TestDeleteMessageAndResendUsrMsgId(t *testing.T) {
"fcm_token": "DUMMY_FCM",
})
uid := r0["user_id"].(string)
sendtok := r0["send_key"].(string)
admintok := r0["admin_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": "Message_1",
"msg_id": "bef8dd3d-078e-4f89-abf4-5258ad22a2e4",
})
@@ -463,7 +459,6 @@ func TestDeleteMessageAndResendUsrMsgId(t *testing.T) {
msg2 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": "Message_1",
"msg_id": "bef8dd3d-078e-4f89-abf4-5258ad22a2e4",
})
@@ -476,7 +471,6 @@ func TestDeleteMessageAndResendUsrMsgId(t *testing.T) {
msg3 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": "Message_1",
"msg_id": "bef8dd3d-078e-4f89-abf4-5258ad22a2e4",
})
@@ -493,7 +487,6 @@ func TestGetMessageSimple(t *testing.T) {
msgOut := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": data.User[0].SendKey,
"user_id": data.User[0].UID,
"title": "Message_1",
})
@@ -533,7 +526,6 @@ func TestGetMessageFull(t *testing.T) {
msgOut := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": data.User[0].SendKey,
"user_id": data.User[0].UID,
"title": "Message_1",
"content": content,
"channel": "demo-channel-007",
@@ -838,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 {
@@ -948,7 +945,6 @@ func TestDeactivatedSubscriptionListMessages(t *testing.T) {
newMessageTitle := langext.RandBase62(48)
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": user15.AdminKey,
"user_id": user15.UID,
"channel": chanName,
"title": newMessageTitle,
})
@@ -1122,7 +1118,6 @@ func TestActiveSubscriptionListMessages(t *testing.T) {
newMessageTitle := langext.RandBase62(48)
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": user15.AdminKey,
"user_id": user15.UID,
"channel": chanName,
"title": newMessageTitle,
})
@@ -1176,7 +1171,6 @@ func TestUnconfirmedSubscriptionListMessages(t *testing.T) {
newMessageTitle := langext.RandBase62(48)
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": user15.AdminKey,
"user_id": user15.UID,
"channel": chanName,
"title": newMessageTitle,
})
@@ -1229,7 +1223,7 @@ func TestListMessagesSubscriptionStatusAllInactiveSubscription(t *testing.T) {
subscriptionID, _ := tt.FindSubscriptionByChanName(t, baseUrl, user14, user15.UID, chanName)
newMessageTitle := langext.RandBase62(48)
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{"key": user15.AdminKey, "user_id": user15.UID, "channel": chanName, "title": newMessageTitle})
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{"key": user15.AdminKey, "channel": chanName, "title": newMessageTitle})
type msg struct {
MessageId string `json:"message_id"`
@@ -1282,7 +1276,7 @@ func TestListMessagesSubscriptionStatusAllNoSubscription(t *testing.T) {
chan2 := data.User[0].Channels[2]
newMessageTitle := langext.RandBase62(48)
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{"key": user0.AdminKey, "user_id": user0.UID, "channel": chan2.InternalName, "title": newMessageTitle})
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{"key": user0.AdminKey, "channel": chan2.InternalName, "title": newMessageTitle})
{
messages := tt.RequestAuthGet[mglist](t, user0.AdminKey, baseUrl, "/api/v2/messages")
@@ -1563,3 +1557,111 @@ func TestListMessagesPaginatedDirectInvalidToken(t *testing.T) {
// Test invalid paginated token (float)
tt.RequestAuthGetShouldFail(t, data.User[16].AdminKey, baseUrl, fmt.Sprintf("/api/v2/messages?page_size=%d&next_page_token=%s", 10, "$1.5"), 400, apierr.PAGETOKEN_ERROR)
}
func TestListMessageDeliveries(t *testing.T) {
_, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
r0 := tt.RequestPost[gin.H](t, baseUrl, "/api/v2/users", gin.H{
"agent_model": "DUMMY_PHONE",
"agent_version": "4X",
"client_type": "ANDROID",
"fcm_token": "DUMMY_FCM",
})
sendtok := r0["send_key"].(string)
admintok := r0["admin_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"title": "Message_1",
})
type delivery struct {
DeliveryID string `json:"delivery_id"`
MessageID string `json:"message_id"`
ReceiverUserID string `json:"receiver_user_id"`
ReceiverClientID string `json:"receiver_client_id"`
Status string `json:"status"`
RetryCount int `json:"retry_count"`
TimestampCreated string `json:"timestamp_created"`
FCMMessageID *string `json:"fcm_message_id"`
}
type deliveryList struct {
Deliveries []delivery `json:"deliveries"`
}
deliveries := tt.RequestAuthGet[deliveryList](t, admintok, baseUrl, "/api/v2/messages/"+fmt.Sprintf("%v", msg1["scn_msg_id"])+"/deliveries")
tt.AssertTrue(t, "deliveries.len >= 1", len(deliveries.Deliveries) >= 1)
tt.AssertEqual(t, "deliveries[0].message_id", fmt.Sprintf("%v", msg1["scn_msg_id"]), deliveries.Deliveries[0].MessageID)
}
func TestListMessageDeliveriesNotFound(t *testing.T) {
ws, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
data := tt.InitDefaultData(t, ws)
tt.RequestAuthGetShouldFail(t, data.User[0].AdminKey, baseUrl, "/api/v2/messages/"+models.NewMessageID().String()+"/deliveries", 404, apierr.MESSAGE_NOT_FOUND)
}
func TestListMessageDeliveriesNoAuth(t *testing.T) {
_, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
r0 := tt.RequestPost[gin.H](t, baseUrl, "/api/v2/users", gin.H{
"agent_model": "DUMMY_PHONE",
"agent_version": "4X",
"client_type": "ANDROID",
"fcm_token": "DUMMY_FCM",
})
sendtok := r0["send_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"title": "Message_1",
})
tt.RequestGetShouldFail(t, baseUrl, "/api/v2/messages/"+fmt.Sprintf("%v", msg1["scn_msg_id"])+"/deliveries", 401, apierr.USER_AUTH_FAILED)
}
func TestListMessageDeliveriesNonAdminKey(t *testing.T) {
_, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
r0 := tt.RequestPost[gin.H](t, baseUrl, "/api/v2/users", gin.H{
"agent_model": "DUMMY_PHONE",
"agent_version": "4X",
"client_type": "ANDROID",
"fcm_token": "DUMMY_FCM",
})
sendtok := r0["send_key"].(string)
readtok := r0["read_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"title": "Message_1",
})
// read key should fail (not admin)
tt.RequestAuthGetShouldFail(t, readtok, baseUrl, "/api/v2/messages/"+fmt.Sprintf("%v", msg1["scn_msg_id"])+"/deliveries", 401, apierr.USER_AUTH_FAILED)
}
func TestListMessageDeliveriesDifferentUserChannel(t *testing.T) {
ws, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
data := tt.InitDefaultData(t, ws)
// User 0 sends a message
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": data.User[0].SendKey,
"title": "Message_from_user_0",
})
// User 1 tries to access deliveries of User 0's message - should fail
tt.RequestAuthGetShouldFail(t, data.User[1].AdminKey, baseUrl, "/api/v2/messages/"+fmt.Sprintf("%v", msg1["scn_msg_id"])+"/deliveries", 401, apierr.USER_AUTH_FAILED)
}
+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()
+36 -48
View File
@@ -1,18 +1,18 @@
package test
import (
"blackforestbytes.com/simplecloudnotifier/api/apierr"
"blackforestbytes.com/simplecloudnotifier/models"
"blackforestbytes.com/simplecloudnotifier/push"
tt "blackforestbytes.com/simplecloudnotifier/test/util"
"fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/gin-gonic/gin"
"math/rand/v2"
"net/url"
"strings"
"testing"
"time"
"blackforestbytes.com/simplecloudnotifier/api/apierr"
"blackforestbytes.com/simplecloudnotifier/push"
tt "blackforestbytes.com/simplecloudnotifier/test/util"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/gin-gonic/gin"
)
func TestSendSimpleMessageJSON(t *testing.T) {
@@ -28,26 +28,22 @@ func TestSendSimpleMessageJSON(t *testing.T) {
"fcm_token": "DUMMY_FCM",
})
uid := r0["user_id"].(string)
admintok := r0["admin_key"].(string)
readtok := r0["read_key"].(string)
sendtok := r0["send_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": "HelloWorld_001",
})
tt.RequestPostShouldFail(t, baseUrl, "/", gin.H{
"key": readtok,
"user_id": uid,
"title": "HelloWorld_001",
}, 401, apierr.USER_AUTH_FAILED)
tt.RequestPostShouldFail(t, baseUrl, "/", gin.H{
"key": "asdf",
"user_id": uid,
"title": "HelloWorld_001",
}, 401, apierr.USER_AUTH_FAILED)
@@ -117,13 +113,11 @@ func TestSendSimpleMessageForm(t *testing.T) {
"fcm_token": "DUMMY_FCM",
})
uid := r0["user_id"].(string)
admintok := r0["admin_key"].(string)
sendtok := r0["send_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", tt.FormData{
"key": sendtok,
"user_id": uid,
"title": "Hello World 9999 [$$$]",
})
@@ -190,7 +184,6 @@ func TestSendSimpleMessageJSONAndQuery(t *testing.T) {
// query overwrite body
msg1 := tt.RequestPost[gin.H](t, baseUrl, fmt.Sprintf("/?user_id=%s&key=%s&title=%s", uid, sendtok, url.QueryEscape("1111111")), gin.H{
"key": "ERR",
"user_id": models.NewUserID(),
"title": "2222222",
})
@@ -212,20 +205,17 @@ func TestSendSimpleMessageAlt1(t *testing.T) {
"fcm_token": "DUMMY_FCM",
})
uid := r0["user_id"].(string)
admintok := r0["admin_key"].(string)
readtok := r0["read_key"].(string)
sendtok := r0["send_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/send", gin.H{
"key": sendtok,
"user_id": uid,
"title": "HelloWorld_001",
})
tt.RequestPostShouldFail(t, baseUrl, "/send", gin.H{
"key": readtok,
"user_id": uid,
"title": "HelloWorld_001",
}, 401, apierr.USER_AUTH_FAILED)
@@ -259,13 +249,11 @@ func TestSendContentMessage(t *testing.T) {
"fcm_token": "DUMMY_FCM",
})
uid := r0["user_id"].(string)
admintok := r0["admin_key"].(string)
sendtok := r0["send_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": "HelloWorld_042",
"content": "I am Content\nasdf",
})
@@ -304,13 +292,11 @@ func TestSendWithSendername(t *testing.T) {
"fcm_token": "DUMMY_FCM",
})
uid := r0["user_id"].(string)
sendtok := r0["send_key"].(string)
admintok := r0["admin_key"].(string)
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": "HelloWorld_xyz",
"content": "Unicode: 日本 - yäy\000\n\t\x00...",
"sender_name": "localhorst",
@@ -353,7 +339,6 @@ func TestSendLongContent(t *testing.T) {
"fcm_token": "DUMMY_FCM",
})
uid := r0["user_id"].(string)
admintok := r0["admin_key"].(string)
sendtok := r0["send_key"].(string)
@@ -364,7 +349,6 @@ func TestSendLongContent(t *testing.T) {
msg1 := tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": sendtok,
"user_id": uid,
"title": "HelloWorld_042",
"content": longContent,
})
@@ -1175,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()
@@ -1190,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{
@@ -1200,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,
@@ -1223,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"])
}
@@ -1252,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()
@@ -1268,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{
@@ -1278,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,
@@ -1301,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{
@@ -1311,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"])
}
+127
View File
@@ -0,0 +1,127 @@
package test
import (
"blackforestbytes.com/simplecloudnotifier/push"
tt "blackforestbytes.com/simplecloudnotifier/test/util"
"fmt"
"github.com/gin-gonic/gin"
"testing"
)
func TestShoutrrrBasic(t *testing.T) {
ws, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
data := tt.InitSingleData(t, ws)
pusher := ws.Pusher.(*push.TestSink)
suffix := fmt.Sprintf("/external/v1/shoutrrr?key=%v", data.SendKey)
_ = tt.RequestPost[gin.H](t, baseUrl, suffix, gin.H{
"title": "Test Title",
"message": "Test Message Content",
})
tt.AssertEqual(t, "messageCount", 1, len(pusher.Data))
tt.AssertStrRepEqual(t, "msg.title", "Test Title", pusher.Last().Message.Title)
tt.AssertStrRepEqual(t, "msg.content", "Test Message Content", pusher.Last().Message.Content)
type mglist struct {
Messages []gin.H `json:"messages"`
}
msgList1 := tt.RequestAuthGet[mglist](t, data.AdminKey, baseUrl, "/api/v2/messages")
tt.AssertEqual(t, "len(messages)", 1, len(msgList1.Messages))
tt.AssertStrRepEqual(t, "msg.title", "Test Title", msgList1.Messages[0]["title"])
tt.AssertStrRepEqual(t, "msg.content", "Test Message Content", msgList1.Messages[0]["content"])
}
func TestShoutrrrChannelNone(t *testing.T) {
ws, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
data := tt.InitSingleData(t, ws)
pusher := ws.Pusher.(*push.TestSink)
suffix := fmt.Sprintf("/external/v1/shoutrrr?key=%v", data.SendKey)
_ = tt.RequestPost[gin.H](t, baseUrl, suffix, gin.H{
"title": "Test Title",
"message": "Test Message",
})
tt.AssertEqual(t, "messageCount", 1, len(pusher.Data))
tt.AssertStrRepEqual(t, "msg.channel", "main", pusher.Last().Message.ChannelInternalName)
}
func TestShoutrrrChannelCustom(t *testing.T) {
ws, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
data := tt.InitSingleData(t, ws)
pusher := ws.Pusher.(*push.TestSink)
suffix := fmt.Sprintf("/external/v1/shoutrrr?key=%v&channel=CTEST", data.SendKey)
_ = tt.RequestPost[gin.H](t, baseUrl, suffix, gin.H{
"title": "Test Title",
"message": "Test Message",
})
tt.AssertEqual(t, "messageCount", 1, len(pusher.Data))
tt.AssertStrRepEqual(t, "msg.channel", "CTEST", pusher.Last().Message.ChannelInternalName)
}
func TestShoutrrrPriorityNone(t *testing.T) {
ws, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
data := tt.InitSingleData(t, ws)
pusher := ws.Pusher.(*push.TestSink)
suffix := fmt.Sprintf("/external/v1/shoutrrr?key=%v", data.SendKey)
_ = tt.RequestPost[gin.H](t, baseUrl, suffix, gin.H{
"title": "Test Title",
"message": "Test Message",
})
tt.AssertEqual(t, "messageCount", 1, len(pusher.Data))
tt.AssertStrRepEqual(t, "msg.priority", 1, pusher.Last().Message.Priority)
}
func TestShoutrrrPrioritySingle(t *testing.T) {
ws, baseUrl, stop := tt.StartSimpleWebserver(t)
defer stop()
data := tt.InitSingleData(t, ws)
pusher := ws.Pusher.(*push.TestSink)
suffix0 := fmt.Sprintf("/external/v1/shoutrrr?key=%v&priority=0", data.SendKey)
_ = tt.RequestPost[gin.H](t, baseUrl, suffix0, gin.H{
"title": "Test Title",
"message": "Test Message",
})
tt.AssertEqual(t, "messageCount", 1, len(pusher.Data))
tt.AssertStrRepEqual(t, "msg.prio", 0, pusher.Last().Message.Priority)
suffix1 := fmt.Sprintf("/external/v1/shoutrrr?key=%v&priority=1", data.SendKey)
_ = tt.RequestPost[gin.H](t, baseUrl, suffix1, gin.H{
"title": "Test Title",
"message": "Test Message",
})
tt.AssertEqual(t, "messageCount", 2, len(pusher.Data))
tt.AssertStrRepEqual(t, "msg.prio", 1, pusher.Last().Message.Priority)
suffix2 := fmt.Sprintf("/external/v1/shoutrrr?key=%v&priority=2", data.SendKey)
_ = tt.RequestPost[gin.H](t, baseUrl, suffix2, gin.H{
"title": "Test Title",
"message": "Test Message",
})
tt.AssertEqual(t, "messageCount", 3, len(pusher.Data))
tt.AssertStrRepEqual(t, "msg.prio", 2, pusher.Last().Message.Priority)
}
+7 -11
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) {
@@ -402,7 +403,6 @@ func TestUserMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1001, 1),
})
@@ -411,7 +411,6 @@ func TestUserMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1002, 1),
})
@@ -419,17 +418,14 @@ func TestUserMessageCounter(t *testing.T) {
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1003, 1),
})
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1004, 1),
})
tt.RequestPost[gin.H](t, baseUrl, "/", gin.H{
"key": admintok,
"user_id": uid,
"title": tt.ShortLipsum(1005, 1),
})
@@ -456,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"]))
@@ -490,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) {
+4 -4
View File
@@ -1,15 +1,16 @@
package util
import (
"blackforestbytes.com/simplecloudnotifier/logic"
"fmt"
"testing"
"time"
"blackforestbytes.com/simplecloudnotifier/logic"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"git.blackforestbytes.com/BlackForestBytes/goext/timeext"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
"gopkg.in/loremipsum.v1"
"testing"
"time"
)
// # Generated by https://chat.openai.com/chat
@@ -393,7 +394,6 @@ func InitDefaultData(t *testing.T, ws *logic.Application) DefData {
for _, mex := range messageExamples {
body := gin.H{}
body["title"] = mex.Title
body["user_id"] = users[mex.User].UID
switch mex.Key {
case AKEY:
body["key"] = users[mex.User].AdminKey
+1 -3
View File
@@ -19,10 +19,9 @@
<a tabindex="-1" href="/" class="linkcaption"><h1>Simple Cloud Notifier</h1></a>
<p>Get your user-id and user-key from the android or iOS app.<br/>And send notifications to your phone by performing a POST request against <code>{{config|baseURL}}/</code> from anywhere</p>
<p>Get your user-key from the android or iOS app.<br/>And send notifications to your phone by performing a POST request against <code>{{config|baseURL}}/</code> from anywhere</p>
<pre>
curl \
--data "user_id=${userid}" \
--data "key=${key}" \
--data "title=${message_title}" \
--data "content=${message_body}" \
@@ -35,7 +34,6 @@ curl \
<p>Most parameters are optional, you can send a message with only a title (default priority and channel will be used)</p>
<pre>
curl \
--data "user_id={userid}" \
--data "key={key}" \
--data "title={message_title}" \
{{config|baseURL}}/</pre>
+2 -7
View File
@@ -52,7 +52,7 @@
All Parameters can either directly be submitted as URL parameters or they can be put into the POST body (either multipart/form-data or JSON).
</p>
<p>
You <i>need</i> to supply a valid <code>[user_id, key]</code> pair and a <code>title</code> for your message, all other parameter are optional.
You <i>need</i> to supply a valid <code>key</code> and a <code>title</code> for your message, all other parameter are optional.
</p>
</div>
@@ -90,7 +90,7 @@
</tr>
<tr>
<td data-label="Statuscode">401 (Unauthorized)</td>
<td data-label="Explanation">The user_id was not found, the key is wrong or the [user_id, key] combination does not have the SEND permissions on the specified channel</td>
<td data-label="Explanation">The key is wrong or does not have the SEND permissions on the specified channel</td>
</tr>
<tr>
<td data-label="Statuscode">403 (Forbidden)</td>
@@ -125,7 +125,6 @@
If needed the content can be supplied in the <code>content</code> parameter.
</p>
<pre>curl \
--data "user_id={userid}" \
--data "key={key}" \
--data "title={message_title}" \
--data "content={message_content}" \
@@ -143,7 +142,6 @@
If no priority is supplied the message will get the default priority of 1.
</p>
<pre>curl \
--data "user_id={userid}" \
--data "key={key}" \
--data "title={message_title}" \
--data "priority={0|1|2}" \
@@ -158,7 +156,6 @@
Channel names are case-insensitive and can only contain letters, numbers, underscores and minuses ( <code>/[[:alnum:]\-_]+/</code> )
</p>
<pre>curl \
--data "user_id={userid}" \
--data "key={key}" \
--data "title={message_title}" \
--data "channel={my_channel}" \
@@ -229,7 +226,6 @@
The message_id is optional - but if you want to use it you need to supply it via the <code>msg_id</code> parameter.
</p>
<pre>curl \
--data "user_id={userid}" \
--data "key={key}" \
--data "title={message_title}" \
--data "msg_id={message_id}" \
@@ -248,7 +244,6 @@
The custom timestamp must be within 48 hours of the current time. This parameter is only intended to supply a more precise value in case the message sending was delayed.
</p>
<pre>curl \
--data "user_id={userid}" \
--data "key={key}" \
--data "title={message_title}" \
--data "timestamp={unix_timestamp}" \
+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;
+3 -5
View File
@@ -17,15 +17,13 @@
<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>
<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>
<div class="row responsive-label">
<div class="col-sm-12 col-md-3"><label for="uid" class="doc">UserID</label></div>
<div class="col-sm-12 col-md"><input placeholder="UserID" id="uid" class="doc" type="text" pattern="USR[A-Za-z0-9]{21}"></div>
</div>
<div class="row responsive-label">
<div class="col-sm-12 col-md-3"><label for="ukey" class="doc">Authentification Key</label></div>
<div class="col-sm-12 col-md"><input placeholder="Key" id="ukey" class="doc" type="text" pattern="[A-Za-z0-9]{64}"></div>
-7
View File
@@ -8,20 +8,17 @@ function send()
me.classList.add("btn-disabled");
let uid = document.getElementById("uid");
let key = document.getElementById("ukey");
let tit = document.getElementById("tit");
let cnt = document.getElementById("cnt");
let pio = document.getElementById("prio");
let cha = document.getElementById("chan");
uid.classList.remove('input-invalid');
key.classList.remove('input-invalid');
cnt.classList.remove('input-invalid');
pio.classList.remove('input-invalid');
let data = new FormData();
data.append('user_id', uid.value);
data.append('key', key.value);
if (tit.value !== '') data.append('title', tit.value);
if (cnt.value !== '') data.append('content', cnt.value);
@@ -40,7 +37,6 @@ function send()
let resp = JSON.parse(xhr.responseText);
if (!resp.success || xhr.status !== 200)
{
if (resp.errhighlight === 101) uid.classList.add('input-invalid');
if (resp.errhighlight === 102) key.classList.add('input-invalid');
if (resp.errhighlight === 103) tit.classList.add('input-invalid');
if (resp.errhighlight === 104) cnt.classList.add('input-invalid');
@@ -63,7 +59,6 @@ function send()
'&quota=' + resp.quota +
'&quota_remain=' + (resp.quota_max-resp.quota) +
'&quota_max=' + resp.quota_max +
'&preset_user_id=' + uid.value +
'&preset_user_key=' + key.value +
'&preset_channel=' + cha.value;
}
@@ -89,7 +84,6 @@ window.addEventListener("load", function ()
const qp = new URLSearchParams(window.location.search);
let btn = document.getElementById("btnSend");
let uid = document.getElementById("uid");
let key = document.getElementById("ukey");
let tit = document.getElementById("tit");
let cnt = document.getElementById("cnt");
@@ -100,7 +94,6 @@ window.addEventListener("load", function ()
if (qp.has('preset_priority')) pio.selectedIndex = parseInt(qp.get("preset_priority"));
if (qp.has('preset_user_key')) key.value = qp.get("preset_user_key");
if (qp.has('preset_user_id')) uid.value = qp.get("preset_user_id");
if (qp.has('preset_title')) tit.value = qp.get("preset_title");
if (qp.has('preset_content')) cnt.value = qp.get("preset_content");
if (qp.has('preset_channel')) cha.value = qp.get("preset_channel");
+50
View File
@@ -0,0 +1,50 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
This is the web application for SimpleCloudNotifier (SCN), a push notification service. It's an Angular 19 standalone component-based SPA using ng-zorro-antd (Ant Design) for UI components.
## Common Commands
- `npm start` - Start development server
- `npm run build` - Production build (outputs to `dist/scn-webapp`)
- `npm run watch` - Development build with watch mode
- `npm test` - Run tests with Karma
## Architecture
### Application Structure
The app follows a feature-based module organization with standalone components:
- `src/app/core/` - Singleton services, guards, interceptors, and data models
- `src/app/features/` - Feature modules (messages, channels, subscriptions, keys, clients, senders, account, auth)
- `src/app/shared/` - Reusable components, directives, and pipes
- `src/app/layout/` - Main layout component with sidebar navigation
### Key Patterns
**Authentication**: Uses a custom `SCN` token scheme. Credentials (user_id and admin_key) are stored in localStorage and attached via `authInterceptor`. The `authGuard` protects all routes except `/login`.
**API Communication**: All API calls go through `ApiService` (`src/app/core/services/api.service.ts`). The base URL is configured in `src/environments/environment.ts`.
**State Management**: Uses Angular signals throughout. No external state library - each component manages its own state with signals.
**Routing**: Lazy-loaded standalone components. All authenticated routes are children of `MainLayoutComponent`.
### Data Models
Models in `src/app/core/models/` correspond to SCN API entities:
- User, Message, Channel, Subscription, KeyToken, Client, SenderName
### UI Framework
Uses ng-zorro-antd with explicit icon imports in `app.config.ts`. Icons must be added to the `icons` array before use.
### Project Configuration
- SCSS for styling
- Strict TypeScript (`strict: true`)
- Component generation skips tests by default (configured in `angular.json`)
+1 -1
View File
@@ -6,7 +6,7 @@ NAMESPACE=$(shell git rev-parse --abbrev-ref HEAD)
HASH=$(shell git rev-parse HEAD)
run:
. ${HOME}/.nvm/nvm.sh && nvm use && npm i && npm run dev
. ${HOME}/.nvm/nvm.sh && nvm use && npm i && npm run start
setup:
npm install
+14
View File
@@ -39,6 +39,13 @@ import {
InfoCircleOutline,
ExclamationCircleOutline,
CheckCircleOutline,
UserAddOutline,
UserDeleteOutline,
PauseCircleOutline,
PlayCircleOutline,
StopOutline,
ArrowLeftOutline,
DownOutline,
} from '@ant-design/icons-angular/icons';
import { routes } from './app.routes';
@@ -79,6 +86,13 @@ const icons: IconDefinition[] = [
InfoCircleOutline,
ExclamationCircleOutline,
CheckCircleOutline,
UserAddOutline,
UserDeleteOutline,
PauseCircleOutline,
PlayCircleOutline,
StopOutline,
ArrowLeftOutline,
DownOutline,
];
export const appConfig: ApplicationConfig = {
+12
View File
@@ -33,14 +33,26 @@ export const routes: Routes = [
path: 'subscriptions',
loadComponent: () => import('./features/subscriptions/subscription-list/subscription-list.component').then(m => m.SubscriptionListComponent)
},
{
path: 'subscriptions/:id',
loadComponent: () => import('./features/subscriptions/subscription-detail/subscription-detail.component').then(m => m.SubscriptionDetailComponent)
},
{
path: 'keys',
loadComponent: () => import('./features/keys/key-list/key-list.component').then(m => m.KeyListComponent)
},
{
path: 'keys/:id',
loadComponent: () => import('./features/keys/key-detail/key-detail.component').then(m => m.KeyDetailComponent)
},
{
path: 'clients',
loadComponent: () => import('./features/clients/client-list/client-list.component').then(m => m.ClientListComponent)
},
{
path: 'clients/:id',
loadComponent: () => import('./features/clients/client-detail/client-detail.component').then(m => m.ClientDetailComponent)
},
{
path: 'senders',
loadComponent: () => import('./features/senders/sender-list/sender-list.component').then(m => m.SenderListComponent)
+4 -3
View File
@@ -7,7 +7,6 @@ export interface Channel {
display_name: string;
description_name: string | null;
subscribe_key?: string;
send_key?: string;
timestamp_created: string;
timestamp_lastsent: string | null;
messages_sent: number;
@@ -22,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';
@@ -34,8 +36,7 @@ export interface CreateChannelRequest {
export interface UpdateChannelRequest {
display_name?: string;
description_name?: string;
subscribe_key?: string;
send_key?: string;
subscribe_key?: boolean; // RefreshSubscribeKey
}
export interface ChannelListResponse {
@@ -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':
@@ -0,0 +1,18 @@
export type DeliveryStatus = 'RETRY' | 'SUCCESS' | 'FAILED';
export interface Delivery {
delivery_id: string;
message_id: string;
receiver_user_id: string;
receiver_client_id: string;
timestamp_created: string;
timestamp_finalized: string | null;
status: DeliveryStatus;
retry_count: number;
next_delivery: string | null;
fcm_message_id: string | null;
}
export interface DeliveryListResponse {
deliveries: Delivery[];
}
+1
View File
@@ -5,4 +5,5 @@ export * from './subscription.model';
export * from './key-token.model';
export * from './client.model';
export * from './sender-name.model';
export * from './delivery.model';
export * from './api-response.model';
@@ -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';
@@ -23,6 +23,7 @@ export interface MessageListParams {
search?: string;
sender?: string[];
subscription_status?: 'all' | 'confirmed' | 'unconfirmed';
used_key?: string;
trimmed?: boolean;
page_size?: number;
next_page_token?: string;
@@ -6,6 +6,7 @@ export interface Subscription {
channel_internal_name: string;
timestamp_created: string;
confirmed: boolean;
active: boolean;
}
export interface SubscriptionFilter {
@@ -25,7 +26,8 @@ export interface CreateSubscriptionRequest {
}
export interface ConfirmSubscriptionRequest {
confirmed: boolean;
confirmed?: boolean;
active?: boolean;
}
export interface SubscriptionListResponse {
@@ -6,6 +6,8 @@ import {
User,
UserWithExtra,
UserPreview,
ChannelPreview,
KeyTokenPreview,
Message,
MessageListParams,
MessageListResponse,
@@ -26,8 +28,10 @@ import {
UpdateKeyRequest,
Client,
ClientListResponse,
ClientPreviewResponse,
SenderNameStatistics,
SenderNameListResponse,
DeliveryListResponse,
} from '../models';
@Injectable({
@@ -92,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();
@@ -152,6 +168,7 @@ export class ApiService {
}
}
if (params.subscription_status) httpParams = httpParams.set('subscription_status', params.subscription_status);
if (params.used_key) httpParams = httpParams.set('used_key', params.used_key);
if (params.trimmed !== undefined) httpParams = httpParams.set('trimmed', params.trimmed);
if (params.page_size) httpParams = httpParams.set('page_size', params.page_size);
if (params.next_page_token) httpParams = httpParams.set('next_page_token', params.next_page_token);
@@ -167,6 +184,10 @@ export class ApiService {
return this.http.delete<Message>(`${this.baseUrl}/messages/${messageId}`);
}
getDeliveries(messageId: string): Observable<DeliveryListResponse> {
return this.http.get<DeliveryListResponse>(`${this.baseUrl}/messages/${messageId}/deliveries`);
}
// Subscription endpoints
getSubscriptions(userId: string, filter?: SubscriptionFilter): Observable<SubscriptionListResponse> {
let httpParams = 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 = sessionStorage.getItem(USER_ID_KEY);
const adminKey = sessionStorage.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 {
sessionStorage.setItem(USER_ID_KEY, userId);
sessionStorage.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 {
sessionStorage.removeItem(USER_ID_KEY);
sessionStorage.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();
}
}
@@ -0,0 +1,58 @@
import { Injectable, inject } from '@angular/core';
import { Observable, of, map, shareReplay, catchError } from 'rxjs';
import { ApiService } from './api.service';
import { AuthService } from './auth.service';
import { KeyToken } from '../models';
export interface ResolvedKey {
keyId: string;
name: string;
}
@Injectable({
providedIn: 'root'
})
export class KeyCacheService {
private apiService = inject(ApiService);
private authService = inject(AuthService);
private keysCache$: Observable<Map<string, KeyToken>> | null = null;
resolveKey(keyId: string): Observable<ResolvedKey> {
return this.getKeysMap().pipe(
map(keysMap => {
const key = keysMap.get(keyId);
return {
keyId,
name: key?.name || keyId
};
})
);
}
private getKeysMap(): Observable<Map<string, KeyToken>> {
const userId = this.authService.getUserId();
if (!userId) {
return of(new Map());
}
if (!this.keysCache$) {
this.keysCache$ = this.apiService.getKeys(userId).pipe(
map(response => {
const map = new Map<string, KeyToken>();
for (const key of response.keys) {
map.set(key.keytoken_id, key);
}
return map;
}),
catchError(() => of(new Map())),
shareReplay(1)
);
}
return this.keysCache$;
}
clearCache(): void {
this.keysCache$ = null;
}
}
@@ -0,0 +1,30 @@
import { Injectable, signal } from '@angular/core';
const EXPERT_MODE_KEY = 'scn_expert_mode';
@Injectable({
providedIn: 'root'
})
export class SettingsService {
private _expertMode = signal(false);
expertMode = this._expertMode.asReadonly();
constructor() {
this.loadFromStorage();
}
private loadFromStorage(): void {
const stored = localStorage.getItem(EXPERT_MODE_KEY);
this._expertMode.set(stored === 'true');
}
setExpertMode(enabled: boolean): void {
localStorage.setItem(EXPERT_MODE_KEY, String(enabled));
this._expertMode.set(enabled);
}
toggleExpertMode(): void {
this.setExpertMode(!this._expertMode());
}
}
@@ -13,36 +13,36 @@
</div>
} @else if (user()) {
<nz-card nzTitle="User Information">
<nz-descriptions nzBordered [nzColumn]="2">
<nz-descriptions-item nzTitle="User ID" [nzSpan]="2">
<scn-metadata-grid>
<scn-metadata-value label="User ID">
<span class="mono">{{ user()!.user_id }}</span>
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Username">
</scn-metadata-value>
<scn-metadata-value label="Username">
{{ user()!.username || '(Not set)' }}
<button nz-button nzSize="small" nzType="link" (click)="openEditModal()">
<span nz-icon nzType="edit"></span>
</button>
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Account Type">
</scn-metadata-value>
<scn-metadata-value label="Account Type">
@if (user()!.is_pro) {
<nz-tag nzColor="gold">Pro</nz-tag>
} @else {
<nz-tag>Free</nz-tag>
}
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Messages Sent">
</scn-metadata-value>
<scn-metadata-value label="Messages Sent">
{{ user()!.messages_sent }}
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Created">
</scn-metadata-value>
<scn-metadata-value label="Created">
{{ user()!.timestamp_created | relativeTime }}
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Last Read">
</scn-metadata-value>
<scn-metadata-value label="Last Read">
{{ user()!.timestamp_lastread | relativeTime }}
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Last Sent">
</scn-metadata-value>
<scn-metadata-value label="Last Sent">
{{ user()!.timestamp_lastsent | relativeTime }}
</nz-descriptions-item>
</nz-descriptions>
</scn-metadata-value>
</scn-metadata-grid>
</nz-card>
<nz-card nzTitle="Quota" class="mt-16">
@@ -62,22 +62,39 @@
<nz-divider></nz-divider>
<nz-descriptions [nzColumn]="2" nzSize="small">
<nz-descriptions-item nzTitle="Max Body Size">
<scn-metadata-grid>
<scn-metadata-value label="Max Body Size">
{{ user()!.max_body_size | number }} bytes
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Max Title Length">
</scn-metadata-value>
<scn-metadata-value label="Max Title Length">
{{ user()!.max_title_length }} chars
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Default Channel">
</scn-metadata-value>
<scn-metadata-value label="Default Channel">
{{ user()!.default_channel }}
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Default Priority">
</scn-metadata-value>
<scn-metadata-value label="Default Priority">
{{ user()!.default_priority }}
</nz-descriptions-item>
</nz-descriptions>
</scn-metadata-value>
</scn-metadata-grid>
</nz-card>
@if (expertMode()) {
<nz-card nzTitle="Danger Zone" class="mt-16 danger-zone">
<p class="danger-warning">Deleting your account is permanent and cannot be undone. All your data will be lost.</p>
<button
nz-button
nzDanger
nz-popconfirm
nzPopconfirmTitle="Are you sure you want to delete your account? This action cannot be undone."
(nzOnConfirm)="deleteAccount()"
[nzLoading]="deleting()"
>
<span nz-icon nzType="delete"></span>
Delete Account
</button>
</nz-card>
}
}
</div>
@@ -43,3 +43,17 @@
margin-bottom: 16px;
}
}
.danger-zone {
border-color: #ff4d4f !important;
:host ::ng-deep .ant-card-head {
color: #ff4d4f;
border-bottom-color: #ff4d4f;
}
.danger-warning {
color: #666;
margin-bottom: 16px;
}
}
@@ -1,6 +1,7 @@
import { Component, inject, signal, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzIconModule } from 'ng-zorro-antd/icon';
@@ -12,11 +13,14 @@ import { NzModalModule } from 'ng-zorro-antd/modal';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzDividerModule } from 'ng-zorro-antd/divider';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
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 { UserWithExtra } from '../../../core/models';
import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
import { MetadataGridComponent, MetadataValueComponent } from '../../../shared/components/metadata-grid';
@Component({
selector: 'app-account-info',
@@ -35,7 +39,10 @@ import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
NzFormModule,
NzInputModule,
NzDividerModule,
NzPopconfirmModule,
RelativeTimePipe,
MetadataGridComponent,
MetadataValueComponent,
],
templateUrl: './account-info.component.html',
styleUrl: './account-info.component.scss'
@@ -44,9 +51,13 @@ export class AccountInfoComponent implements OnInit {
private apiService = inject(ApiService);
private authService = inject(AuthService);
private notification = inject(NotificationService);
private settingsService = inject(SettingsService);
private router = inject(Router);
user = signal<UserWithExtra | null>(null);
loading = signal(true);
deleting = signal(false);
expertMode = this.settingsService.expertMode;
// Edit username modal
showEditModal = signal(false);
@@ -116,4 +127,26 @@ export class AccountInfoComponent implements OnInit {
}
});
}
deleteAccount(): void {
const userId = this.authService.getUserId();
if (!userId) return;
this.deleting.set(true);
this.apiService.deleteUser(userId).subscribe({
next: () => {
this.notification.success('Account deleted');
this.authService.logout();
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);
}
});
}
}
@@ -14,59 +14,37 @@
></nz-alert>
}
<form nz-form nzLayout="horizontal" (ngSubmit)="login()">
<nz-form-item>
<nz-form-label [nzSpan]="7">User ID</nz-form-label>
<nz-form-control [nzSpan]="17">
<nz-input-group nzPrefixIcon="user">
<div class="login-form">
<label for="userId">User ID</label>
<input
id="userId"
type="text"
nz-input
placeholder="Enter your User ID"
[(ngModel)]="userId"
name="userId"
[disabled]="loading()"
/>
</nz-input-group>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-label [nzSpan]="7">Admin Key</nz-form-label>
<nz-form-control [nzSpan]="17">
<nz-input-group nzPrefixIcon="key" [nzSuffix]="keySuffix">
<label for="adminKey">Admin Key</label>
<input
[type]="showKey() ? 'text' : 'password'"
id="adminKey"
type="text"
nz-input
placeholder="Enter your Admin Key"
[(ngModel)]="adminKey"
name="adminKey"
[disabled]="loading()"
/>
</nz-input-group>
<ng-template #keySuffix>
<span
nz-icon
[nzType]="showKey() ? 'eye' : 'eye-invisible'"
class="key-toggle"
(click)="toggleShowKey()"
></span>
</ng-template>
</nz-form-control>
</nz-form-item>
</div>
<nz-form-item class="mb-0">
<button
nz-button
nzType="primary"
nzBlock
type="submit"
[nzLoading]="loading()"
(click)="login()"
>
Sign In
</button>
</nz-form-item>
</form>
<div class="login-footer">
<p>You need an admin key to access.</p>
@@ -9,7 +9,7 @@
.login-card {
width: 100%;
max-width: 400px;
max-width: 650px;
border-radius: 8px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}
@@ -38,13 +38,15 @@
}
}
.key-toggle {
cursor: pointer;
color: #999;
transition: color 0.3s;
.login-form {
display: grid;
grid-template-columns: auto 1fr;
gap: 12px 16px;
align-items: center;
margin-bottom: 16px;
&:hover {
color: #1890ff;
label {
font-weight: 500;
}
}
@@ -58,7 +60,3 @@
color: #999;
}
}
nz-form-label {
font-weight: 500;
}
@@ -1,14 +1,11 @@
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 { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzAlertModule } from 'ng-zorro-antd/alert';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { AuthService } from '../../../core/services/auth.service';
import { ApiService } from '../../../core/services/api.service';
import { isAdminKey } from '../../../core/models';
@@ -19,13 +16,10 @@ import { isAdminKey } from '../../../core/models';
imports: [
CommonModule,
FormsModule,
NzFormModule,
NzInputModule,
NzButtonModule,
NzCardModule,
NzAlertModule,
NzIconModule,
NzSpinModule,
],
templateUrl: './login.component.html',
styleUrl: './login.component.scss'
@@ -33,14 +27,12 @@ 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 = '';
adminKey = '';
loading = signal(false);
error = signal<string | null>(null);
showKey = signal(false);
async login(): Promise<void> {
if (!this.userId.trim() || !this.adminKey.trim()) {
@@ -63,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();
@@ -80,8 +74,4 @@ export class LoginComponent {
}
});
}
toggleShowKey(): void {
this.showKey.update(v => !v);
}
}
@@ -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>
@@ -15,65 +15,69 @@
<span nz-icon nzType="edit"></span>
Edit
</button>
@if (expertMode()) {
<button
nz-button
nzType="primary"
nzDanger
nz-popconfirm
nzPopconfirmTitle="Are you sure you want to delete this channel? All messages and subscriptions will be lost."
nzPopconfirmPlacement="bottomRight"
(nzOnConfirm)="deleteChannel()"
[nzLoading]="deleting()"
>
<span nz-icon nzType="delete"></span>
Delete
</button>
}
</div>
}
</div>
<nz-card [nzTitle]="channel()!.display_name">
<nz-descriptions nzBordered [nzColumn]="2">
<nz-descriptions-item nzTitle="Channel ID" [nzSpan]="2">
<span class="mono">{{ channel()!.channel_id }}</span>
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Internal Name">
<span class="mono">{{ channel()!.internal_name }}</span>
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Status">
<nz-card [nzTitle]="channelData()!.display_name">
<scn-metadata-grid>
<scn-metadata-value label="Channel ID">
<span class="mono">{{ channelData()!.channel_id }}</span>
</scn-metadata-value>
<scn-metadata-value label="Internal Name">
<span class="mono">{{ channelData()!.internal_name }}</span>
</scn-metadata-value>
<scn-metadata-value label="Status">
<nz-tag [nzColor]="getSubscriptionStatus().color">
{{ getSubscriptionStatus().label }}
</nz-tag>
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Owner" [nzSpan]="2">
<span class="mono">{{ channel()!.owner_user_id }}</span>
</nz-descriptions-item>
@if (channel()!.description_name) {
<nz-descriptions-item nzTitle="Description" [nzSpan]="2">
{{ channel()!.description_name }}
</nz-descriptions-item>
</scn-metadata-value>
<scn-metadata-value label="Owner">
@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>
}
<nz-descriptions-item nzTitle="Messages Sent">
{{ channel()!.messages_sent }}
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Last Sent">
</scn-metadata-value>
@if (channelData()!.description_name) {
<scn-metadata-value label="Description">
{{ channelData()!.description_name }}
</scn-metadata-value>
}
<scn-metadata-value label="Messages Sent">
{{ channelData()!.messages_sent }}
</scn-metadata-value>
@if (channel()) {
<scn-metadata-value label="Last Sent">
@if (channel()!.timestamp_lastsent) {
{{ channel()!.timestamp_lastsent | relativeTime }}
<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
}
</nz-descriptions-item>
<nz-descriptions-item nzTitle="Created" [nzSpan]="2">
{{ channel()!.timestamp_created }}
</nz-descriptions-item>
</nz-descriptions>
</nz-card>
@if (isOwner()) {
<nz-card nzTitle="Keys" class="mt-16">
@if (channel()!.subscribe_key) {
<div class="key-section">
<label>Subscribe Key</label>
</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">
<input
type="text"
@@ -93,63 +97,44 @@
[appCopyToClipboard]="channel()!.subscribe_key!"
></span>
</ng-template>
<div class="key-actions">
@if (expertMode()) {
<button
nz-button
nzSize="small"
nz-popconfirm
nzPopconfirmTitle="Regenerate subscribe key? The existing key will no longer be valid."
(nzOnConfirm)="regenerateSubscribeKey()"
>
Invalidate & Regenerate
</button>
</div>
<div class="qr-section">
<app-qr-code-display [data]="qrCodeData()"></app-qr-code-display>
<p class="qr-hint">Scan this QR code with the SimpleCloudNotifier app to subscribe to this channel.</p>
</div>
</div>
}
</div>
</scn-metadata-value>
<scn-metadata-value label="Subscribe QR">
<div class="qr-container">
<app-qr-code-display [data]="qrCodeData()"></app-qr-code-display>
<p class="qr-hint">Scan with the SimpleCloudNotifier app to subscribe</p>
</div>
</scn-metadata-value>
}
</scn-metadata-grid>
</nz-card>
@if (channel()!.send_key) {
<nz-divider></nz-divider>
<div class="key-section">
<label>Send Key</label>
<nz-input-group [nzSuffix]="sendKeySuffix">
<input
type="text"
nz-input
[value]="channel()!.send_key"
readonly
class="mono"
/>
</nz-input-group>
<ng-template #sendKeySuffix>
<span
nz-icon
nzType="copy"
class="action-icon"
nz-tooltip
nzTooltipTitle="Copy"
[appCopyToClipboard]="channel()!.send_key!"
></span>
</ng-template>
<div class="key-actions">
@if (isOwner()) {
<nz-card nzTitle="Subscriptions" [nzExtra]="subscriptionsCardExtra" class="mt-16">
<ng-template #subscriptionsCardExtra>
@if (expertMode()) {
<button
nz-button
nzSize="small"
nz-popconfirm
nzPopconfirmTitle="Regenerate send key?"
(nzOnConfirm)="regenerateSendKey()"
[nzType]="isUserSubscribed() ? 'default' : 'primary'"
nz-tooltip
[nzTooltipTitle]="isUserSubscribed() ? 'Unsubscribe' : 'Subscribe'"
(click)="toggleSelfSubscription()"
>
Regenerate
<span nz-icon [nzType]="isUserSubscribed() ? 'user-delete' : 'user-add'"></span>
</button>
</div>
</div>
}
</nz-card>
<nz-card nzTitle="Subscriptions" class="mt-16">
</ng-template>
<nz-table
#subscriptionTable
[nzData]="subscriptions()"
@@ -162,26 +147,88 @@
<thead>
<tr>
<th>Subscriber</th>
<th>Status</th>
<th>Created</th>
<th nzWidth="0">Status</th>
<th nzWidth="0">Active</th>
<th nzWidth="0">Created</th>
<th nzWidth="0">Actions</th>
</tr>
</thead>
<tbody>
@for (sub of subscriptions(); track sub.subscription_id) {
<tr>
<tr class="clickable-row">
<td>
<span class="mono">{{ sub.subscriber_user_id }}</span>
<a class="cell-link" [routerLink]="['/subscriptions', sub.subscription_id]">
<div class="cell-name">{{ getUserDisplayName(sub.subscriber_user_id) }}</div>
<div class="cell-id mono">{{ sub.subscriber_user_id }}</div>
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/subscriptions', sub.subscription_id]">
<nz-tag [nzColor]="sub.confirmed ? 'green' : 'orange'">
{{ sub.confirmed ? 'Confirmed' : 'Pending' }}
</nz-tag>
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/subscriptions', sub.subscription_id]">
<nz-tag [nzColor]="sub.active ? 'green' : 'default'">
{{ sub.active ? 'Active' : 'Inactive' }}
</nz-tag>
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/subscriptions', sub.subscription_id]">
<div class="timestamp-absolute">{{ sub.timestamp_created | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ sub.timestamp_created | relativeTime }}</div>
</a>
</td>
<td>
<div class="action-buttons">
@if (!sub.confirmed) {
<button
nz-button
nzSize="small"
nzType="primary"
nz-tooltip
nzTooltipTitle="Accept"
(click)="acceptSubscription(sub)"
>
<span nz-icon nzType="check"></span>
</button>
<button
nz-button
nzSize="small"
nzDanger
nz-tooltip
nzTooltipTitle="Deny"
nz-popconfirm
nzPopconfirmTitle="Deny this subscription request?"
(nzOnConfirm)="denySubscription(sub)"
>
<span nz-icon nzType="close"></span>
</button>
} @else {
@if (expertMode()) {
<button
nz-button
nzSize="small"
nzDanger
nz-tooltip
nzTooltipTitle="Revoke"
nz-popconfirm
nzPopconfirmTitle="Revoke this subscription?"
(nzOnConfirm)="revokeSubscription(sub)"
>
<span nz-icon nzType="delete"></span>
</button>
}
}
</div>
</td>
<td>{{ sub.timestamp_created | relativeTime }}</td>
</tr>
} @empty {
<tr>
<td colspan="3">
<td colspan="5">
<nz-empty nzNotFoundContent="No subscriptions"></nz-empty>
</td>
</tr>
@@ -190,6 +237,84 @@
</nz-table>
</nz-card>
}
<nz-card nzTitle="Messages" class="mt-16">
<nz-table
#messageTable
[nzData]="messages()"
[nzLoading]="loadingMessages()"
[nzShowPagination]="false"
[nzNoResult]="noMessagesResultTpl"
nzSize="small"
>
<ng-template #noMessagesResultTpl></ng-template>
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th nzWidth="0">Sender</th>
<th nzWidth="0">Priority</th>
<th nzWidth="0">Time</th>
</tr>
</thead>
<tbody>
@for (message of messages(); track message.message_id) {
<tr class="clickable-row">
<td>
<a class="cell-link" [routerLink]="['/messages', message.message_id]">
<div class="message-title">{{ message.title }}</div>
<div class="message-id mono">{{ message.message_id }}</div>
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/messages', message.message_id]">
@if (message.content) {
<div class="message-content">{{ message.content | slice:0:128 }}{{ message.content.length > 128 ? '...' : '' }}</div>
} @else {
<span class="text-muted"></span>
}
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/messages', message.message_id]">
<span style="white-space: pre">{{ message.sender_name || '-' }}</span>
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/messages', message.message_id]">
<nz-tag [nzColor]="getPriorityColor(message.priority)">
{{ getPriorityLabel(message.priority) }}
</nz-tag>
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/messages', message.message_id]">
<div class="timestamp-absolute">{{ message.timestamp | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ message.timestamp | relativeTime }}</div>
</a>
</td>
</tr>
} @empty {
<tr>
<td colspan="5">
<nz-empty nzNotFoundContent="No messages"></nz-empty>
</td>
</tr>
}
</tbody>
</nz-table>
@if (messagesTotalCount() > messagesPageSize) {
<div class="pagination-controls">
<nz-pagination
[nzPageIndex]="messagesCurrentPage()"
[nzPageSize]="messagesPageSize"
[nzTotal]="messagesTotalCount()"
[nzDisabled]="loadingMessages()"
(nzPageIndexChange)="messagesGoToPage($event)"
></nz-pagination>
</div>
}
</nz-card>
} @else {
<nz-card>
<div class="not-found">
@@ -10,17 +10,14 @@
gap: 8px;
}
.key-section {
label {
display: block;
font-weight: 500;
margin-bottom: 8px;
color: #333;
}
.key-field {
display: flex;
flex-direction: row;
gap: 8px;
}
.key-actions {
margin-top: 8px;
display: flex;
}
.action-icon {
@@ -44,28 +41,92 @@
}
}
.qr-section {
margin-top: 16px;
padding-top: 16px;
border-top: 1px solid #f0f0f0;
label {
display: block;
font-weight: 500;
margin-bottom: 12px;
color: #333;
}
app-qr-code-display {
.qr-container {
display: flex;
justify-content: center;
}
flex-direction: column;
align-items: center;
}
.qr-hint {
text-align: center;
color: #666;
font-size: 13px;
margin-top: 12px;
margin-top: 8px;
margin-bottom: 0;
}
.cell-name {
font-weight: 500;
color: #333;
}
.cell-id {
font-size: 11px;
color: #999;
margin-top: 2px;
}
.timestamp-absolute {
font-size: 13px;
color: #333;
white-space: pre;
}
.timestamp-relative {
font-size: 12px;
color: #999;
white-space: pre;
}
.clickable-row {
cursor: pointer;
&:hover {
background-color: #fafafa;
}
}
.action-buttons {
display: flex;
gap: 4px;
}
.message-title {
font-weight: 500;
color: #333;
}
.message-id {
font-size: 11px;
color: #999;
margin-top: 2px;
}
.message-content {
font-size: 12px;
color: #666;
white-space: pre;
max-height: 2lh;
overflow-y: clip;
}
.owner-name {
font-weight: 500;
color: #333;
}
.owner-id {
font-size: 11px;
color: #999;
margin-top: 2px;
}
.text-muted {
color: #999;
}
.pagination-controls {
display: flex;
justify-content: center;
align-items: center;
padding: 16px 0;
}
@@ -1,11 +1,10 @@
import { Component, inject, signal, computed, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { CommonModule, DatePipe } from '@angular/common';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzDescriptionsModule } from 'ng-zorro-antd/descriptions';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
@@ -16,24 +15,29 @@ import { NzFormModule } from 'ng-zorro-antd/form';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzToolTipModule } from 'ng-zorro-antd/tooltip';
import { NzEmptyModule } from 'ng-zorro-antd/empty';
import { NzPaginationModule } from 'ng-zorro-antd/pagination';
import { ApiService } from '../../../core/services/api.service';
import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { ChannelWithSubscription, Subscription } from '../../../core/models';
import { SettingsService } from '../../../core/services/settings.service';
import { UserCacheService, ResolvedUser } from '../../../core/services/user-cache.service';
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';
import { MetadataGridComponent, MetadataValueComponent } from '../../../shared/components/metadata-grid';
@Component({
selector: 'app-channel-detail',
standalone: true,
imports: [
CommonModule,
DatePipe,
FormsModule,
RouterLink,
NzCardModule,
NzButtonModule,
NzIconModule,
NzDescriptionsModule,
NzTagModule,
NzSpinModule,
NzPopconfirmModule,
@@ -44,9 +48,12 @@ import { QrCodeDisplayComponent } from '../../../shared/components/qr-code-displ
NzTableModule,
NzToolTipModule,
NzEmptyModule,
NzPaginationModule,
RelativeTimePipe,
CopyToClipboardDirective,
QrCodeDisplayComponent,
MetadataGridComponent,
MetadataValueComponent,
],
templateUrl: './channel-detail.component.html',
styleUrl: './channel-detail.component.scss'
@@ -57,13 +64,26 @@ export class ChannelDetailComponent implements OnInit {
private apiService = inject(ApiService);
private authService = inject(AuthService);
private notification = inject(NotificationService);
private settingsService = inject(SettingsService);
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);
deleting = signal(false);
expertMode = this.settingsService.expertMode;
// Messages pagination
messagesPageSize = 16;
messagesNextPageToken = signal<string | null>(null);
messagesTotalCount = signal(0);
messagesCurrentPage = signal(1);
// Edit modal
showEditModal = signal(false);
editDisplayName = '';
@@ -97,12 +117,25 @@ export class ChannelDetailComponent implements OnInit {
if (!userId) return;
this.loading.set(true);
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);
if (this.isOwner()) {
this.loadSubscriptions(channelId);
this.loadMessages(channelId);
},
error: () => {
this.loading.set(false);
}
});
} else {
this.loading.set(false);
this.loadMessages(channelId);
}
},
error: () => {
@@ -120,6 +153,7 @@ export class ChannelDetailComponent implements OnInit {
next: (response) => {
this.subscriptions.set(response.subscriptions);
this.loadingSubscriptions.set(false);
this.resolveUserNames(response.subscriptions);
},
error: () => {
this.loadingSubscriptions.set(false);
@@ -127,14 +161,106 @@ export class ChannelDetailComponent implements OnInit {
});
}
loadMessages(channelId: string, nextPageToken?: string): void {
this.loadingMessages.set(true);
this.apiService.getMessages({
channel_id: [channelId],
page_size: this.messagesPageSize,
next_page_token: nextPageToken,
trimmed: true,
subscription_status: 'all'
}).subscribe({
next: (response) => {
this.messages.set(response.messages);
this.messagesNextPageToken.set(response.next_page_token || null);
this.messagesTotalCount.set(response.total_count);
this.loadingMessages.set(false);
},
error: () => {
this.loadingMessages.set(false);
}
});
}
messagesGoToPage(page: number): void {
const channel = this.channel();
if (!channel) return;
this.messagesCurrentPage.set(page);
// For pagination with tokens, we need to handle this differently
// The API uses next_page_token, so we'll reload from the beginning for now
// In a real implementation, you'd need to track tokens per page or use offset-based pagination
if (page === 1) {
this.loadMessages(channel.channel_id);
} else {
// For simplicity, use the next page token if going forward
const token = this.messagesNextPageToken();
if (token) {
this.loadMessages(channel.channel_id, token);
}
}
}
viewMessage(message: Message): void {
this.router.navigate(['/messages', message.message_id]);
}
getPriorityColor(priority: number): string {
switch (priority) {
case 0: return 'default';
case 1: return 'blue';
case 2: return 'orange';
default: return 'default';
}
}
getPriorityLabel(priority: number): string {
switch (priority) {
case 0: return 'Low';
case 1: return 'Normal';
case 2: return 'High';
default: return 'Unknown';
}
}
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) {
userIds.add(sub.subscriber_user_id);
}
for (const id of userIds) {
this.userCacheService.resolveUser(id).subscribe(resolved => {
this.userNames.update(map => new Map(map).set(id, resolved));
});
}
}
getUserDisplayName(userId: string): string {
const resolved = this.userNames().get(userId);
return resolved?.displayName || userId;
}
goBack(): void {
this.router.navigate(['/channels']);
}
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
@@ -173,7 +299,45 @@ export class ChannelDetailComponent implements OnInit {
});
}
// Delete channel
// Regenerate keys
regenerateSubscribeKey(): void {
const channel = this.channel();
const userId = this.authService.getUserId();
if (!channel || !userId) return;
this.apiService.updateChannel(userId, channel.channel_id, {
subscribe_key: true
}).subscribe({
next: (updated) => {
this.channel.set(updated);
this.notification.success('Subscribe key regenerated');
}
});
}
getSubscriptionStatus(): { label: string; color: string } {
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 (subscription) {
return { label: 'Owned & Subscribed', color: 'green' };
}
return { label: 'Owned', color: 'blue' };
}
if (subscription) {
if (subscription.confirmed) {
return { label: 'Subscribed', color: 'green' };
}
return { label: 'Pending', color: 'orange' };
}
return { label: 'Not Subscribed', color: 'default' };
}
deleteChannel(): void {
const channel = this.channel();
const userId = this.authService.getUserId();
@@ -191,55 +355,81 @@ export class ChannelDetailComponent implements OnInit {
});
}
// Regenerate keys
regenerateSubscribeKey(): void {
const channel = this.channel();
const userId = this.authService.getUserId();
if (!channel || !userId) return;
viewSubscription(sub: Subscription): void {
this.router.navigate(['/subscriptions', sub.subscription_id]);
}
this.apiService.updateChannel(userId, channel.channel_id, {
subscribe_key: 'true'
}).subscribe({
next: (updated) => {
this.channel.set(updated);
this.notification.success('Subscribe key regenerated');
acceptSubscription(sub: Subscription): void {
const userId = this.authService.getUserId();
if (!userId) return;
this.apiService.confirmSubscription(userId, sub.subscription_id, { confirmed: true }).subscribe({
next: () => {
this.notification.success('Subscription accepted');
const channel = this.channel();
if (channel) {
this.loadSubscriptions(channel.channel_id);
}
}
});
}
regenerateSendKey(): void {
const channel = this.channel();
denySubscription(sub: Subscription): void {
const userId = this.authService.getUserId();
if (!channel || !userId) return;
if (!userId) return;
this.apiService.updateChannel(userId, channel.channel_id, {
send_key: 'true'
}).subscribe({
next: (updated) => {
this.channel.set(updated);
this.notification.success('Send key regenerated');
this.apiService.deleteSubscription(userId, sub.subscription_id).subscribe({
next: () => {
this.notification.success('Subscription denied');
const channel = this.channel();
if (channel) {
this.loadSubscriptions(channel.channel_id);
}
}
});
}
getSubscriptionStatus(): { label: string; color: string } {
revokeSubscription(sub: Subscription): void {
const userId = this.authService.getUserId();
if (!userId) return;
this.apiService.deleteSubscription(userId, sub.subscription_id).subscribe({
next: () => {
this.notification.success('Subscription revoked');
const channel = this.channel();
if (!channel) return { label: 'Unknown', color: 'default' };
if (this.isOwner()) {
if (channel.subscription) {
return { label: 'Owned & Subscribed', color: 'green' };
if (channel) {
this.loadSubscriptions(channel.channel_id);
}
return { label: 'Owned', color: 'blue' };
}
});
}
if (channel.subscription) {
if (channel.subscription.confirmed) {
return { label: 'Subscribed', color: 'green' };
}
return { label: 'Pending', color: 'orange' };
isUserSubscribed(): boolean {
return this.channelData()?.subscription !== null && this.channelData()?.subscription !== undefined;
}
return { label: 'Not Subscribed', color: 'default' };
toggleSelfSubscription(): void {
const channel = this.channel();
const userId = this.authService.getUserId();
if (!channel || !userId) return;
if (this.isUserSubscribed()) {
// Unsubscribe
const subscriptionId = channel.subscription!.subscription_id;
this.apiService.deleteSubscription(userId, subscriptionId).subscribe({
next: () => {
this.notification.success('Unsubscribed from channel');
this.loadChannel(channel.channel_id);
}
});
} else {
// Subscribe
this.apiService.createSubscription(userId, { channel_id: channel.channel_id }).subscribe({
next: () => {
this.notification.success('Subscribed to channel');
this.loadChannel(channel.channel_id);
}
});
}
}
}
@@ -9,6 +9,21 @@
</div>
</div>
<nz-tabset (nzSelectedIndexChange)="onTabChange($event)">
<nz-tab nzTitle="All"></nz-tab>
<nz-tab nzTitle="Owned"></nz-tab>
<nz-tab nzTitle="Foreign"></nz-tab>
</nz-tabset>
@if (getTabDescription()) {
<nz-alert
nzType="info"
[nzMessage]="getTabDescription()!"
nzShowIcon
style="margin-bottom: 16px;"
></nz-alert>
}
<nz-card>
<nz-table
#channelTable
@@ -21,46 +36,89 @@
<ng-template #noResultTpl></ng-template>
<thead>
<tr>
<th nzWidth="20%">Name</th>
<th nzWidth="15%">Internal Name</th>
<th nzWidth="15%">Owner</th>
<th nzWidth="15%">Status</th>
<th nzWidth="15%">Messages</th>
<th nzWidth="20%">Last Sent</th>
<th style="width: auto">Name</th>
<th style="width: auto">Internal Name</th>
<th style="width: auto">Owner</th>
<th style="width: 0">Status</th>
<th style="width: 400px">Subscribers</th>
<th style="width: 0">Messages</th>
<th style="width: 0">Last Sent</th>
@if (expertMode()) {
<th style="width: 0">Actions</th>
}
</tr>
</thead>
<tbody>
@for (channel of channels(); track channel.channel_id) {
<tr class="clickable-row" (click)="viewChannel(channel)">
<tr class="clickable-row">
<td>
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<div class="channel-name">{{ channel.display_name }}</div>
@if (channel.description_name) {
<div class="channel-description">{{ channel.description_name }}</div>
}
<div class="channel-id mono">{{ channel.channel_id }}</div>
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<span class="mono">{{ channel.internal_name }}</span>
</a>
</td>
<td>{{ getOwnerDisplayName(channel.owner_user_id) }}</td>
<td>
<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>
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<nz-tag [nzColor]="getSubscriptionStatus(channel).color">
{{ getSubscriptionStatus(channel).label }}
</nz-tag>
</a>
</td>
<td>{{ channel.messages_sent }}</td>
<td>
@if (isOwned(channel)) {
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
<app-channel-subscribers [channelId]="channel.channel_id" />
</a>
} @else {
<span class="text-muted">-</span>
}
</td>
<td>
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
{{ channel.messages_sent }}
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/channels', channel.channel_id]">
@if (channel.timestamp_lastsent) {
<span nz-tooltip [nzTooltipTitle]="channel.timestamp_lastsent">
{{ channel.timestamp_lastsent | relativeTime }}
</span>
<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>
@if (isOwned(channel)) {
<button
nz-button
nzSize="small"
[nzType]="channel.subscription ? 'default' : 'primary'"
nz-tooltip
[nzTooltipTitle]="channel.subscription ? 'Unsubscribe' : 'Subscribe'"
(click)="toggleSelfSubscription(channel, $event)"
>
<span nz-icon [nzType]="channel.subscription ? 'user-delete' : 'user-add'"></span>
</button>
}
</td>
}
</tr>
} @empty {
<tr>
<td colspan="6">
<td [attr.colspan]="expertMode() ? 8 : 7">
<nz-empty nzNotFoundContent="No channels found"></nz-empty>
</td>
</tr>
@@ -23,12 +23,32 @@
color: #333;
}
.channel-description {
font-size: 12px;
.channel-id {
font-size: 11px;
color: #999;
margin-top: 4px;
margin-top: 2px;
}
.text-muted {
color: #999;
}
.timestamp-absolute {
font-size: 13px;
color: #333;
white-space: pre;
}
.timestamp-relative {
font-size: 12px;
color: #999;
white-space: pre;
}
.clickable-row {
cursor: pointer;
&:hover {
background-color: #fafafa;
}
}
@@ -1,6 +1,6 @@
import { Component, inject, signal, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';
import { Component, inject, signal, computed, OnInit } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import { Router, RouterLink } from '@angular/router';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzIconModule } from 'ng-zorro-antd/icon';
@@ -9,17 +9,26 @@ import { NzBadgeModule } from 'ng-zorro-antd/badge';
import { NzEmptyModule } from 'ng-zorro-antd/empty';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzToolTipModule } from 'ng-zorro-antd/tooltip';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { NzAlertModule } from 'ng-zorro-antd/alert';
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 { UserCacheService, ResolvedUser } from '../../../core/services/user-cache.service';
import { ChannelWithSubscription } from '../../../core/models';
import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
import { ChannelSubscribersComponent } from '../channel-subscribers/channel-subscribers.component';
type ChannelTab = 'all' | 'owned' | 'foreign';
@Component({
selector: 'app-channel-list',
standalone: true,
imports: [
CommonModule,
DatePipe,
RouterLink,
NzTableModule,
NzButtonModule,
NzIconModule,
@@ -28,7 +37,10 @@ import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
NzEmptyModule,
NzCardModule,
NzToolTipModule,
NzTabsModule,
NzAlertModule,
RelativeTimePipe,
ChannelSubscribersComponent,
],
templateUrl: './channel-list.component.html',
styleUrl: './channel-list.component.scss'
@@ -36,12 +48,31 @@ import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
export class ChannelListComponent implements OnInit {
private apiService = inject(ApiService);
private authService = inject(AuthService);
private notification = inject(NotificationService);
private settingsService = inject(SettingsService);
private userCacheService = inject(UserCacheService);
private router = inject(Router);
channels = signal<ChannelWithSubscription[]>([]);
allChannels = signal<ChannelWithSubscription[]>([]);
ownerNames = signal<Map<string, ResolvedUser>>(new Map());
loading = signal(false);
expertMode = this.settingsService.expertMode;
activeTab = signal<ChannelTab>('all');
channels = computed(() => {
const userId = this.authService.getUserId();
const all = this.allChannels();
const tab = this.activeTab();
switch (tab) {
case 'owned':
return all.filter(c => c.owner_user_id === userId);
case 'foreign':
return all.filter(c => c.owner_user_id !== userId);
default:
return all;
}
});
ngOnInit(): void {
this.loadChannels();
@@ -54,7 +85,7 @@ export class ChannelListComponent implements OnInit {
this.loading.set(true);
this.apiService.getChannels(userId, 'all_any').subscribe({
next: (response) => {
this.channels.set(response.channels);
this.allChannels.set(response.channels);
this.loading.set(false);
this.resolveOwnerNames(response.channels);
},
@@ -64,6 +95,22 @@ export class ChannelListComponent implements OnInit {
});
}
onTabChange(index: number): void {
const tabs: ChannelTab[] = ['all', 'owned', 'foreign'];
this.activeTab.set(tabs[index]);
}
getTabDescription(): string | null {
switch (this.activeTab()) {
case 'owned':
return 'Channels that you own and can configure.';
case 'foreign':
return 'Channels owned by other users that you are subscribed to.';
default:
return null;
}
}
private resolveOwnerNames(channels: ChannelWithSubscription[]): void {
const uniqueOwnerIds = [...new Set(channels.map(c => c.owner_user_id))];
for (const ownerId of uniqueOwnerIds) {
@@ -78,6 +125,10 @@ export class ChannelListComponent implements OnInit {
return resolved?.displayName || ownerId;
}
isOwned(channel: ChannelWithSubscription): boolean {
return channel.owner_user_id === this.authService.getUserId();
}
viewChannel(channel: ChannelWithSubscription): void {
this.router.navigate(['/channels', channel.channel_id]);
}
@@ -101,4 +152,28 @@ export class ChannelListComponent implements OnInit {
return { label: 'Not Subscribed', color: 'default' };
}
toggleSelfSubscription(channel: ChannelWithSubscription, event: Event): void {
event.stopPropagation();
const userId = this.authService.getUserId();
if (!userId) return;
if (channel.subscription) {
// Unsubscribe
this.apiService.deleteSubscription(userId, channel.subscription.subscription_id).subscribe({
next: () => {
this.notification.success('Unsubscribed from channel');
this.loadChannels();
}
});
} else {
// Subscribe
this.apiService.createSubscription(userId, { channel_id: channel.channel_id }).subscribe({
next: () => {
this.notification.success('Subscribed to channel');
this.loadChannels();
}
});
}
}
}
@@ -0,0 +1,107 @@
import { Component, inject, input, signal, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { NzToolTipModule } from 'ng-zorro-antd/tooltip';
import { ApiService } from '../../../core/services/api.service';
import { AuthService } from '../../../core/services/auth.service';
import { UserCacheService, ResolvedUser } from '../../../core/services/user-cache.service';
import { Subscription } from '../../../core/models';
@Component({
selector: 'app-channel-subscribers',
standalone: true,
imports: [CommonModule, NzSpinModule, NzToolTipModule],
template: `
@if (loading()) {
<nz-spin nzSimple nzSize="small"></nz-spin>
} @else if (subscribers().length === 0) {
<span class="text-muted">None</span>
} @else {
<div class="subscribers-list">
@for (sub of subscribers(); track sub.subscription_id) {
<span
class="subscriber"
[class.unconfirmed]="!sub.confirmed"
nz-tooltip
[nzTooltipTitle]="getTooltip(sub)"
>
{{ getDisplayName(sub.subscriber_user_id) }}
</span>
}
</div>
}
`,
styles: [`
.text-muted {
color: #999;
}
.subscribers-list {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.subscriber {
background: #f0f0f0;
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
}
.subscriber.unconfirmed {
background: #fff7e6;
color: #d48806;
}
`]
})
export class ChannelSubscribersComponent implements OnInit {
private apiService = inject(ApiService);
private authService = inject(AuthService);
private userCacheService = inject(UserCacheService);
channelId = input.required<string>();
loading = signal(true);
subscribers = signal<Subscription[]>([]);
userNames = signal<Map<string, ResolvedUser>>(new Map());
ngOnInit(): void {
this.loadSubscribers();
}
private loadSubscribers(): void {
const userId = this.authService.getUserId();
if (!userId) {
this.loading.set(false);
return;
}
this.apiService.getChannelSubscriptions(userId, this.channelId()).subscribe({
next: (response) => {
this.subscribers.set(response.subscriptions);
this.loading.set(false);
this.resolveUserNames(response.subscriptions);
},
error: () => {
this.loading.set(false);
}
});
}
private resolveUserNames(subscriptions: Subscription[]): void {
const userIds = new Set(subscriptions.map(s => s.subscriber_user_id));
for (const userId of userIds) {
this.userCacheService.resolveUser(userId).subscribe(resolved => {
this.userNames.update(map => new Map(map).set(userId, resolved));
});
}
}
getDisplayName(userId: string): string {
const resolved = this.userNames().get(userId);
return resolved?.displayName || userId;
}
getTooltip(sub: Subscription): string {
const status = sub.confirmed ? 'Confirmed' : 'Pending';
return `${sub.subscriber_user_id} (${status})`;
}
}
@@ -0,0 +1,76 @@
<div class="page-content">
@if (loading()) {
<div class="loading-container">
<nz-spin nzSimple nzSize="large"></nz-spin>
</div>
} @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 (isOwner() && expertMode()) {
<div class="header-actions">
<button
nz-button
nzDanger
nz-popconfirm
nzPopconfirmTitle="Are you sure you want to delete this client?"
(nzOnConfirm)="deleteClient()"
>
<span nz-icon nzType="delete"></span>
Delete
</button>
</div>
}
</div>
<nz-card>
<div class="client-header">
<span
nz-icon
[nzType]="getClientIcon(clientData()!.type)"
nzTheme="outline"
class="client-type-icon"
></span>
<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">{{ clientData()!.client_id }}</span>
</scn-metadata-value>
<scn-metadata-value label="Type">
<nz-tag>{{ getClientTypeLabel(clientData()!.type) }}</nz-tag>
</scn-metadata-value>
<scn-metadata-value label="Agent">
<div class="agent-info">
<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">{{ 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 {
<nz-card>
<div class="not-found">
<p>Client not found</p>
<button nz-button nzType="primary" (click)="goBack()">
Back to Clients
</button>
</div>
</nz-card>
}
</div>
@@ -0,0 +1,69 @@
.loading-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 300px;
}
.header-actions {
display: flex;
gap: 8px;
}
.client-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
.client-type-icon {
font-size: 24px;
color: #666;
}
.client-title {
margin: 0;
font-size: 20px;
font-weight: 500;
}
.agent-info {
display: flex;
flex-direction: column;
.agent-version {
font-size: 12px;
color: #999;
}
}
.fcm-token {
display: block;
max-width: 300px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.not-found {
text-align: center;
padding: 48px;
p {
color: #999;
margin-bottom: 16px;
}
}
.timestamp-absolute {
font-size: 13px;
color: #333;
white-space: pre;
}
.timestamp-relative {
font-size: 12px;
color: #999;
white-space: pre;
}
@@ -0,0 +1,131 @@
import { Component, inject, signal, OnInit } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
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 { Client, ClientPreview, ClientType, getClientTypeIcon } from '../../../core/models';
import { RelativeTimePipe } from '../../../shared/pipes/relative-time.pipe';
import { MetadataGridComponent, MetadataValueComponent } from '../../../shared/components/metadata-grid';
@Component({
selector: 'app-client-detail',
standalone: true,
imports: [
CommonModule,
DatePipe,
NzCardModule,
NzButtonModule,
NzIconModule,
NzTagModule,
NzSpinModule,
NzPopconfirmModule,
NzToolTipModule,
RelativeTimePipe,
MetadataGridComponent,
MetadataValueComponent,
],
templateUrl: './client-detail.component.html',
styleUrl: './client-detail.component.scss'
})
export class ClientDetailComponent implements OnInit {
private route = inject(ActivatedRoute);
private router = inject(Router);
private apiService = inject(ApiService);
private authService = inject(AuthService);
private notification = inject(NotificationService);
private settingsService = inject(SettingsService);
client = signal<Client | null>(null);
clientPreview = signal<ClientPreview | null>(null);
loading = signal(true);
expertMode = this.settingsService.expertMode;
ngOnInit(): void {
const clientId = this.route.snapshot.paramMap.get('id');
if (clientId) {
this.loadClient(clientId);
}
}
loadClient(clientId: string): void {
const userId = this.authService.getUserId();
if (!userId) return;
this.loading.set(true);
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);
}
});
}
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']);
}
getClientIcon(type: ClientType): string {
return getClientTypeIcon(type);
}
getClientTypeLabel(type: ClientType): string {
switch (type) {
case 'ANDROID': return 'Android';
case 'IOS': return 'iOS';
case 'MACOS': return 'macOS';
case 'WINDOWS': return 'Windows';
case 'LINUX': return 'Linux';
default: return type;
}
}
deleteClient(): void {
const client = this.client();
const userId = this.authService.getUserId();
if (!client || !userId) return;
this.apiService.deleteClient(userId, client.client_id).subscribe({
next: () => {
this.notification.success('Client deleted');
this.router.navigate(['/clients']);
}
});
}
}
@@ -19,47 +19,55 @@
<ng-template #noResultTpl></ng-template>
<thead>
<tr>
<th nzWidth="5%"></th>
<th nzWidth="20%">Name</th>
<th nzWidth="15%">Type</th>
<th nzWidth="25%">Agent</th>
<th nzWidth="20%">Created</th>
<th nzWidth="15%">Client ID</th>
<th nzWidth="0"></th>
<th>Name</th>
<th nzWidth="0">Type</th>
<th nzWidth="0">Agent</th>
<th nzWidth="0">Created</th>
</tr>
</thead>
<tbody>
@for (client of clients(); track client.client_id) {
<tr>
<tr class="clickable-row">
<td>
<a class="cell-link" [routerLink]="['/clients', client.client_id]">
<span
nz-icon
[nzType]="getClientIcon(client.type)"
nzTheme="outline"
class="client-icon"
></span>
</a>
</td>
<td>{{ client.name || '-' }}</td>
<td>
<a class="cell-link" [routerLink]="['/clients', client.client_id]">
<div class="client-name">{{ client.name || '-' }}</div>
<div class="client-id mono">{{ client.client_id }}</div>
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/clients', client.client_id]">
<nz-tag>{{ getClientTypeLabel(client.type) }}</nz-tag>
</a>
</td>
<td>
<a class="cell-link" [routerLink]="['/clients', client.client_id]">
<div class="agent-info">
<span>{{ client.agent_model }}</span>
<span class="agent-version">v{{ client.agent_version }}</span>
<span style="white-space: pre;">{{ client.agent_model }}</span>
<span style="white-space: pre;" class="agent-version">v{{ client.agent_version }}</span>
</div>
</a>
</td>
<td>
<span nz-tooltip [nzTooltipTitle]="client.timestamp_created">
{{ client.timestamp_created | relativeTime }}
</span>
</td>
<td>
<span class="mono client-id">{{ client.client_id }}</span>
<a class="cell-link" [routerLink]="['/clients', client.client_id]">
<div class="timestamp-absolute">{{ client.timestamp_created | date:'yyyy-MM-dd HH:mm:ss' }}</div>
<div class="timestamp-relative">{{ client.timestamp_created | relativeTime }}</div>
</a>
</td>
</tr>
} @empty {
<tr>
<td colspan="6">
<td colspan="5">
<nz-empty nzNotFoundContent="No clients registered"></nz-empty>
</td>
</tr>

Some files were not shown because too many files have changed in this diff Show More