Skip to content

Commit

Permalink
Merge pull request #109 from humhub/95-notification-opens-the-dashboa…
Browse files Browse the repository at this point in the history
…rd-instead-of-the-related-content

Use the def. notification chanel and fix the on terminated msg redirect.
  • Loading branch information
luke- authored Sep 12, 2023
2 parents fcc54f8 + d9771a2 commit b30025c
Show file tree
Hide file tree
Showing 11 changed files with 194 additions and 224 deletions.
64 changes: 32 additions & 32 deletions android/build.gradle
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
buildscript {
ext.kotlin_version = '1.6.10'
repositories {
google()
mavenCentral()
}

dependencies {
classpath 'com.android.tools.build:gradle:7.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.15'
}
}

allprojects {
repositories {
google()
mavenCentral()
}
}

rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
delete rootProject.buildDir
}
buildscript {
ext.kotlin_version = '1.6.10'
repositories {
google()
mavenCentral()
}

dependencies {
classpath 'com.android.tools.build:gradle:7.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.15'
}
}

allprojects {
repositories {
google()
mavenCentral()
}
}

rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}

tasks.register("clean", Delete) {
delete rootProject.buildDir
}
42 changes: 21 additions & 21 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import 'package:humhub/util/push/push_plugin.dart';
import 'package:humhub/util/router.dart';
import 'package:loggy/loggy.dart';

main() {
main() async {
Loggy.initLoggy(
logPrinter: const GlobalLog(),
);
Expand All @@ -24,26 +24,26 @@ class MyApp extends ConsumerStatefulWidget {
class MyAppState extends ConsumerState<MyApp> {
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: MyRouter.getInitialRoute(ref),
builder: (context, snap) {
if (snap.hasData) {
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: snap.data,
routes: MyRouter.routes,
navigatorKey: navigatorKey,
theme: ThemeData(
fontFamily: 'OpenSans',
),
builder: (context, child) {
return NotificationPlugin(
child: PushPlugin(child: child!),
);
});
}
return const SizedBox.shrink();
},
return NotificationPlugin(
child: PushPlugin(
child: FutureBuilder<String>(
future: MyRouter.getInitialRoute(ref),
builder: (context, snap) {
if (snap.hasData) {
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: snap.data,
routes: MyRouter.routes,
navigatorKey: navigatorKey,
theme: ThemeData(
fontFamily: 'OpenSans',
),
);
}
return const SizedBox.shrink();
},
),
),
);
}
}
9 changes: 9 additions & 0 deletions lib/pages/web_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ import 'package:humhub/models/manifest.dart';
import 'package:humhub/pages/opener.dart';
import 'package:humhub/util/connectivity_plugin.dart';
import 'package:humhub/util/extensions.dart';
import 'package:humhub/util/notifications/channel.dart';
import 'package:humhub/util/providers.dart';
import 'package:humhub/util/push_opener_controller.dart';
import 'package:humhub/util/router.dart';
import 'package:loggy/loggy.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:humhub/util/router.dart' as m;
Expand Down Expand Up @@ -195,6 +197,13 @@ class WebViewAppState extends ConsumerState<WebViewApp> {
if (args == null) {
manifest = m.MyRouter.initParams;
}
if (args is ManifestWithRemoteMsg) {
ManifestWithRemoteMsg manifestPush = args;
manifest = manifestPush.manifest;
url = manifestPush.remoteMessage.data['url'];
}
String? payloadFromPush = RedirectNotificationChannel.usePayloadForInit();
if (payloadFromPush != null) url = payloadFromPush;
return URLRequest(url: Uri.parse(url ?? manifest.baseUrl), headers: ref.read(humHubProvider).customHeaders);
}

Expand Down
61 changes: 20 additions & 41 deletions lib/util/notifications/channel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,18 @@ import 'package:humhub/util/push_opener_controller.dart';
import 'package:humhub/util/router.dart';
import 'package:loggy/loggy.dart';

/// Used to group notifications by Android channels
///
/// How to use: subclass this abstract class and override onTap method. Then
/// pass instance of this subclass to [NotificationService.scheduleNotification]
/// which will take care of calling [onTap] on correct channel.
abstract class NotificationChannel {
final String id;
final String name;
final String description;

NotificationChannel(this.id, this.name, this.description);

static final List<NotificationChannel> _knownChannels = [
GeneralNotificationChannel(),
];

static bool canAcceptTap(String? channelId) {
final result = _knownChannels.any((element) => element.id == channelId);

if (!result) {
logError("Error on channelId: $channelId");
}
return result;
}

factory NotificationChannel.fromId(String? id) => _knownChannels.firstWhere(
(channel) => id == channel.id,
);

Future<void> onTap(String? payload);

@protected
Future<void> navigate(String route, {Object? arguments}) async {
logDebug('navigate: $route');
if (navigatorKey.currentState?.mounted ?? false) {
await navigatorKey.currentState?.pushNamed(
route,
Expand All @@ -52,28 +31,14 @@ abstract class NotificationChannel {
}
}

class GeneralNotificationChannel extends NotificationChannel {
GeneralNotificationChannel()
: super(
'general',
'General app notifications',
'These notifications don\'t belong to any other category.',
);

@override
Future<void> onTap(String? payload) async {
if (payload != null) {
logInfo("Here we do navigate to specific screen for channel");
}
}
}

class RedirectNotificationChannel extends NotificationChannel {
static String? _redirectUrlFromInit;

RedirectNotificationChannel()
: super(
'general',
'General app notifications',
'These notifications don\'t belong to any other category.',
'redirect',
'Redirect app notifications',
'These notifications are redirect the user to specific url in a payload.',
);

/// If the WebView is not opened yet or the app is not running the onTap will wake up the app or redirect to the WebView.
Expand All @@ -96,6 +61,20 @@ class RedirectNotificationChannel extends NotificationChannel {
return;
}
navigatorKey.currentState!.pushNamed(WebViewApp.path, arguments: opener);
} else {
if (payload != null) {
setPayloadForInit(payload);
}
}
}

static setPayloadForInit(String payload) {
_redirectUrlFromInit = payload;
}

static String? usePayloadForInit() {
String? payload = _redirectUrlFromInit;
_redirectUrlFromInit = null;
return payload;
}
}
73 changes: 16 additions & 57 deletions lib/util/notifications/service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -49,34 +49,12 @@ class NotificationService {
static void handleNotification(NotificationResponse response) async {
logDebug('_handleNotification PushPlugin');
final parsed = response.payload != null ? json.decode(response.payload!) : {};
if (!NotificationChannel.canAcceptTap(parsed['channel_id'])) return;
if(parsed["redirectUrl"] != null){
if (parsed["redirectUrl"] != null) {
await RedirectNotificationChannel().onTap(parsed['redirectUrl']);
return;
}
await NotificationChannel.fromId(parsed['channel_id']).onTap(parsed['payload']);
}

NotificationDetails _details(
Color? color,
NotificationChannel channel,
) =>
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
importance: Importance.max,
priority: Priority.high,
largeIcon: const DrawableResourceAndroidBitmap('@mipmap/ic_launcher'),
color: color,
),
);

/// Example:
/// ```dart
///await NotificationPlugin.of(context).showNotification(...);
/// ```
Future<void> showNotification(
NotificationChannel channel,
String? title,
Expand All @@ -85,12 +63,7 @@ class NotificationService {
String? redirectUrl,
ThemeData? theme,
}) async {
final newPayload = {
'channel_id': channel.id,
'payload': payload,
'redirectUrl': redirectUrl
};

final newPayload = {'channel_id': channel.id, 'payload': payload, 'redirectUrl': redirectUrl};
await plugin.show(
int.parse(DateTime.now().microsecondsSinceEpoch.toString().replaceRange(0, 7, '')),
title,
Expand All @@ -100,35 +73,21 @@ class NotificationService {
);
}

/// Example:
/// ```dart
///await NotificationPlugin.of(context).scheduleNotification(...);
/// ```
/// Make sure you call [initializeTimeZone] beforehand!
Future<void> scheduleNotification(
NotificationDetails _details(
Color? color,
NotificationChannel channel,
String? title,
String? description,
Duration duration, {
String? payload,
ThemeData? theme,
}) async {
final newPayload = {
'channel_id': channel.id,
'payload': payload,
};

await plugin.zonedSchedule(
0,
title,
description,
TZDateTime.now(local).add(duration),
_details(theme?.primaryColor, channel),
payload: jsonEncode(newPayload),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.wallClockTime,
);
}
) =>
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
importance: Importance.max,
priority: Priority.high,
largeIcon: const DrawableResourceAndroidBitmap('@mipmap/ic_launcher'),
color: color,
),
);
}

final notificationProvider = StateProvider<NotificationService?>(
Expand Down
Loading

0 comments on commit b30025c

Please sign in to comment.