Moved notification handling to serverside

This commit is contained in:
Elias Müller 2023-09-08 20:54:01 +02:00
parent 5f0426aab9
commit 6816e77d21
5 changed files with 77 additions and 86 deletions

View File

@ -1,46 +1,45 @@
import 'dart:developer';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import '../api/marianumcloud/talk/room/getRoom.dart'; import '../model/chatList/chatListProps.dart';
import '../api/marianumcloud/talk/room/getRoomParams.dart'; import '../model/message/messageProps.dart';
import '../model/accountData.dart';
import 'notificationService.dart';
class NotificationController { class NotificationController {
@pragma('vm:entry-point') @pragma('vm:entry-point')
static Future<void> onBackgroundMessageHandler(RemoteMessage message) async { static Future<void> onBackgroundMessageHandler(RemoteMessage message) async {
log("Handling a background notification: ${message.messageId}"); return; // Displaying the notification is curently done via the Firebase SDK itself. The Message is server-generated.
// log("Handling a background notification: ${message.messageId}");
await Firebase.initializeApp(); //
AccountData().waitForPopulation().then((value) { // await Firebase.initializeApp();
log("User account status: $value"); // AccountData().waitForPopulation().then((value) {
if(value) { // log("User account status: $value");
GetRoom( // if(value) {
GetRoomParams( // GetRoom(
includeStatus: false, // GetRoomParams(
), // includeStatus: false,
).run().then((value) { // ),
var messageCount = value.data.map((e) => e.unreadMessages).reduce((a, b) => a + b); // ).run().then((value) {
var chatCount = value.data.where((e) => e.unreadMessages > 0).length; // var messageCount = value.data.map((e) => e.unreadMessages).reduce((a, b) => a + b);
var people = value.data.where((e) => e.unreadMessages > 0).map((e) => e.displayName.split(" ")[0]); // var chatCount = value.data.where((e) => e.unreadMessages > 0).length;
// var people = value.data.where((e) => e.unreadMessages > 0).map((e) => e.displayName.split(" ")[0]);
final NotificationService service = NotificationService(); //
service.initializeNotifications().then((value) { // final NotificationService service = NotificationService();
service.showNotification( // service.initializeNotifications().then((value) {
title: "Du hast $messageCount ungelesene Nachrichten!", // service.showNotification(
body: "In $chatCount Chats, von ${people.join(", ")}", // title: "Du hast $messageCount ungelesene Nachrichten!",
badgeCount: messageCount, // body: "In $chatCount Chats, von ${people.join(", ")}",
); // badgeCount: messageCount,
}); // );
}); // });
} // });
}); // }
// });
} }
static Future<void> onForegroundMessageHandler(RemoteMessage message, BuildContext context) async { static Future<void> onForegroundMessageHandler(RemoteMessage message, BuildContext context) async {
NotificationService().showToast(message: "Du hast eine neue Talk Nachricht!", context: context); //NotificationService().showToast(message: "Du hast eine neue Talk Nachricht!", context: context);
Provider.of<ChatListProps>(context, listen: false).run(renew: true);
Provider.of<MessageProps>(context, listen: false).run(renew: true);
} }
} }

View File

@ -1,10 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:fluttertoast/fluttertoast.dart'; import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import '../model/chatList/chatListProps.dart';
import '../model/message/messageProps.dart';
class NotificationService { class NotificationService {
static final NotificationService _instance = NotificationService._internal(); static final NotificationService _instance = NotificationService._internal();
@ -73,8 +69,5 @@ class NotificationService {
textColor: Colors.white, textColor: Colors.white,
fontSize: 13.0, fontSize: 13.0,
); );
Provider.of<ChatListProps>(context, listen: false).run(renew: true);
Provider.of<MessageProps>(context, listen: false).run(renew: true);
} }
} }

View File

@ -1,9 +1,15 @@
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:developer';
import 'package:crypto/crypto.dart';
import 'package:fast_rsa/fast_rsa.dart';
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import '../api/mhsl/notify/register/notifyRegister.dart'; import '../api/mhsl/notify/register/notifyRegister.dart';
import '../api/mhsl/notify/register/notifyRegisterParams.dart'; import '../api/mhsl/notify/register/notifyRegisterParams.dart';
import '../model/accountData.dart'; import '../model/accountData.dart';
import '../model/endpointData.dart';
class NotifyUpdater { class NotifyUpdater {
static void registerToServer() async { static void registerToServer() async {
@ -19,4 +25,40 @@ class NotifyUpdater {
), ),
).run(); ).run();
} }
static Future<void> registerNcPush() async {
log("Starting");
log("Generate keys");
final rsaKey = await RSA.generate(2048);
final devicePrivateKey = rsaKey.privateKey.toString();
final devicePublicKey = rsaKey.publicKey.toString();
log("Private: \n$devicePrivateKey");
log("Public: \n$devicePublicKey");
final pushToken = await FirebaseMessaging.instance.getToken();
log("PushToken: $pushToken}");
final pushTokenHash = sha512.convert(utf8.encode(pushToken!));
log("PushTokenHash: $pushTokenHash");
final requestMap = {
"format": "json",
"pushTokenHash": pushTokenHash.toString(),
"devicePublicKey": devicePublicKey.replaceAll("\n", "").replaceAll("-----END RSA PUBLIC KEY-----", "").replaceAll("-----BEGIN RSA PUBLIC KEY-----", "").toString(),
"proxyServer": "https://push-notifications.nextcloud.com/devices"
};
log(jsonEncode(requestMap));
http.post(
//${AccountData().buildHttpAuthString()}@
Uri.parse("https://${EndpointData().nextcloud().full()}/ocs/v2.php/apps/notifications/api/v2/push"),
headers: {
"OCS-APIRequest": "true",
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer Fv3g7g9jW91FXNjZLaJmyprClfy8pX1jEM3hJGbXjPEFcx4oGIEVcpwEnuT4mPs39D9xT063"
},
body: jsonEncode(requestMap),
).then((response) {
log("Response: ${response.statusCode}\n${response.body}");
});
}
} }

View File

@ -6,11 +6,11 @@ import 'package:flowder/flowder.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart'; import 'package:jiffy/jiffy.dart';
import 'package:marianum_mobile/widget/centeredLeading.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import '../../../api/marianumcloud/webdav/queries/listFiles/cacheableFile.dart'; import '../../../api/marianumcloud/webdav/queries/listFiles/cacheableFile.dart';
import '../../../api/marianumcloud/webdav/webdavApi.dart'; import '../../../api/marianumcloud/webdav/webdavApi.dart';
import '../../../widget/centeredLeading.dart';
import '../../../widget/confirmDialog.dart'; import '../../../widget/confirmDialog.dart';
import '../../../widget/fileViewer.dart'; import '../../../widget/fileViewer.dart';
import '../../../widget/unimplementedDialog.dart'; import '../../../widget/unimplementedDialog.dart';

View File

@ -1,18 +1,9 @@
import 'dart:convert';
import 'dart:developer';
import 'package:http/http.dart' as http;
import 'package:crypto/crypto.dart';
import 'package:fast_rsa/fast_rsa.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:persistent_bottom_nav_bar/persistent_tab_view.dart'; import 'package:persistent_bottom_nav_bar/persistent_tab_view.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
import '../../../model/endpointData.dart';
import '../../../widget/ListItem.dart'; import '../../../widget/ListItem.dart';
import '../../../widget/debug/debugTile.dart';
import '../../settings/settings.dart'; import '../../settings/settings.dart';
import 'gradeAverages/gradeAverage.dart'; import 'gradeAverages/gradeAverage.dart';
import 'holidays/holidays.dart'; import 'holidays/holidays.dart';
@ -38,6 +29,7 @@ class Overhang extends StatelessWidget {
const ListItemNavigator(icon: Icons.room, text: "Raumplan", target: Roomplan()), const ListItemNavigator(icon: Icons.room, text: "Raumplan", target: Roomplan()),
const ListItemNavigator(icon: Icons.calculate, text: "Notendurschnittsrechner", target: GradeAverage()), const ListItemNavigator(icon: Icons.calculate, text: "Notendurschnittsrechner", target: GradeAverage()),
const ListItemNavigator(icon: Icons.calendar_month, text: "Schulferien", target: Holidays()), const ListItemNavigator(icon: Icons.calendar_month, text: "Schulferien", target: Holidays()),
const Divider(),
ListTile( ListTile(
leading: const Icon(Icons.share_outlined), leading: const Icon(Icons.share_outlined),
title: const Text("Teile die App"), title: const Text("Teile die App"),
@ -56,41 +48,6 @@ class Overhang extends StatelessWidget {
); );
}, },
), ),
DebugTile(context, onlyInDebug: true).callback(onTab: () async {
log("Starting");
log("Generate keys");
final rsaKey = await RSA.generate(2048);
final devicePrivateKey = rsaKey.privateKey.toString();
final devicePublicKey = rsaKey.publicKey.toString();
log("Private: \n$devicePrivateKey");
log("Public: \n$devicePublicKey");
final pushToken = await FirebaseMessaging.instance.getToken();
log("PushToken: $pushToken}");
final pushTokenHash = sha512.convert(utf8.encode(pushToken!));
log("PushTokenHash: $pushTokenHash");
final requestMap = {
"format": "json",
"pushTokenHash": pushTokenHash.toString(),
"devicePublicKey": devicePublicKey.replaceAll("\n", "").replaceAll("-----END RSA PUBLIC KEY-----", "").replaceAll("-----BEGIN RSA PUBLIC KEY-----", "").toString(),
"proxyServer": "https://push-notifications.nextcloud.com/devices"
};
log(jsonEncode(requestMap));
http.post(
//${AccountData().buildHttpAuthString()}@
Uri.parse("https://${EndpointData().nextcloud().full()}/ocs/v2.php/apps/notifications/api/v2/push"),
headers: {
"OCS-APIRequest": "true",
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer Fv3g7g9jW91FXNjZLaJmyprClfy8pX1jEM3hJGbXjPEFcx4oGIEVcpwEnuT4mPs39D9xT063"
},
body: jsonEncode(requestMap),
).then((response) {
log("Response: ${response.statusCode}\n${response.body}");
});
}),
], ],
), ),
); );