Skip to content

Commit

Permalink
Added Firebase cloud messaging in app + cloud functions, if new data …
Browse files Browse the repository at this point in the history
…is available
  • Loading branch information
RolandDaum committed Jun 19, 2024
1 parent 625b177 commit f01f599
Show file tree
Hide file tree
Showing 15 changed files with 203 additions and 30 deletions.
4 changes: 2 additions & 2 deletions Firebase/functions/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Firebase/functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "^12.1.0",
"firebase-admin": "^12.1.1",
"firebase-functions": "^5.0.0",
"selenium-webdriver": "^4.21.0"
},
Expand Down
60 changes: 44 additions & 16 deletions Firebase/functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {Builder, By, until} from "selenium-webdriver";
import {Options} from "selenium-webdriver/chrome";
import * as admin from "firebase-admin";
import {log} from "firebase-functions/logger";
import {Message} from "firebase-admin/lib/messaging/messaging-api";

// Firebase Admin SDK initialisieren
admin.initializeApp();
Expand Down Expand Up @@ -85,24 +86,26 @@ async function uuidFunction(): Promise<number[]> {
counter++;
}

if (uuids.length != 0) {
if (uuids.length > 0) {
// ---- THIS DID NOT WORK ---- unessesary don't use it again
// const previousUUIDS: string[] = [];
// try {
// const snapshot = await admin.database().ref("/URL").once("value");
// snapshot.forEach((childSnapshot) => {
// const uuid = childSnapshot.child("uuid").val();
// if (uuid) {
// previousUUIDS.push(uuid);
// }
// });
// } catch (error) {
// log("E R R O R : " + error);
// }
// TODO: Is this really nessecary? Cause the timestamps won't beupdated.
// if (!(uuids.toString() === previousUUIDS.toString())) {
const previousUUIDS: string[] = [];
try {
const snapshot = await admin.database().ref("/URL").once("value");
snapshot.forEach((childSnapshot) => {
const uuid = childSnapshot.child("uuid").val();
if (uuid) {
previousUUIDS.push(uuid);
}
});
} catch (error) {
log("E R R O R : " + error);
}
await saveUUIDsToDatabase(uuids);
// }
log(uuids.toString() != previousUUIDS.toString() +
" -> if true, sending notification");
if (uuids.toString() != previousUUIDS.toString()) {
sendNotification(uuids);
}
}
const endtime = Date.now();
return [starttime, endtime];
Expand Down Expand Up @@ -165,3 +168,28 @@ async function saveUUIDsToDatabase(uuids: string[]): Promise<void> {
});
}
}

/**
* Takes the uuids and sends them with the notification
* @param {string[]} uuids
*/
async function sendNotification(uuids:string[]) {
const message:Message = {
notification: {
title: "New VPlan",
body: "new data",
},
data: {
uuids: uuids.toString(),
},
topic: "everyone",
android: {
notification: {
icon: "https://cdn.discordapp.com/attachments/1131545299291222037/1252956973335318559/Frame_6.png?ex=66741a9d&is=6672c91d&hm=559603924d4e07a5bbc4add388a4b8687438a1914be81d599df6246685e62215&",
},
},
};
await admin.messaging().send(message).catch((error) => {
log(`Error: ${error}`);
});
}
4 changes: 4 additions & 0 deletions gbevplan/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/> <!-- Else Im getting a ERR_CHACHE_MISS in webview -->
<uses-permission android:name="android.permission.VIBRATE" /> <!-- In order to use Haptic Feedback -->
<uses-permission android:name="android.permision.RECEIVE_BOOT_COMPLETED"/> <!-- CHANGED FOR LOCAL NOTIFICATIONS-->
<application
android:label="gbevplan"
android:name="${applicationName}"
Expand All @@ -27,11 +28,14 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />


</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
Expand Down
Empty file added gbevplan/flutter_01.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
78 changes: 76 additions & 2 deletions gbevplan/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:dynamic_color/dynamic_color.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gbevplan/firebase_options.dart';
Expand All @@ -10,13 +12,82 @@ import 'package:gbevplan/pages/home_screens/HomeNews.dart';
import 'package:gbevplan/pages/home_screens/HomeOGTimeTable.dart';
import 'package:gbevplan/pages/home_screens/HomeSettings.dart';
import 'package:gbevplan/pages/login.dart';
import 'package:gbevplan/pages/test.dart';
import 'package:google_fonts/google_fonts.dart';

main() async {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print("ON BACKGROUNDMESSAGE");
// navigatorKey.currentState?.pushNamed("/PAGE_TEST",
// arguments: "YOU GOT A NOTIFICATION WHILE THE APP WAS CLOSED");
print(message.notification?.title);

// TODO: Process the new data
await Future.delayed(const Duration(seconds: 5));

// https://www.youtube.com/watch?v=MTGAFvF1qVI&ab_channel=HussainMustafa
if (message.notification?.title != null) {
AwesomeNotifications().createNotification(
content: NotificationContent(
id: 123,
channelKey: "localchannel",
title: "U P D A T E D - T I M E T A B L E",
body: "t i m e t a b l e"));
}
}

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);

// Local Notification
await AwesomeNotifications().initialize(null, [
NotificationChannel(
channelGroupKey: "localChannel_Group",
channelKey: "localchannel",
channelName: "Local Notification Channel",
channelDescription: "Local Notification Channel"),
// icon: ""
], channelGroups: [
NotificationChannelGroup(
channelGroupKey: "localChannel_Group",
channelGroupName: "Local Notification Channel Group")
]);
if (!await AwesomeNotifications().isNotificationAllowed()) {
AwesomeNotifications().requestPermissionToSendNotifications();
}

// F I R E B A S E - M E S S A G I N G
await FirebaseMessaging.instance.requestPermission(
// alert: true,
// announcement: false,
// badge: true,
// carPlay: false,
// criticalAlert: false,
// provisional: false,
// sound: true,
);
FirebaseMessaging.instance.subscribeToTopic("everyone");
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print("ON MESSAGE");
navigatorKey.currentState?.pushNamed("/PAGE_TEST",
arguments: "YOU GOT A NOTIFICATION WHILE BEING INSIDE THE APP");
});
FirebaseMessaging.onMessageOpenedApp.listen((message) {
print("ON MESSAGE opend APP");
navigatorKey.currentState
?.pushNamed("/PAGE_TEST", arguments: "YOU TAPPED ON THE NOTIFICATION");
});
FirebaseMessaging.instance.getToken().then((token) {
print(token);
});

// Navigation/Notification Bar Style
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
statusBarIconBrightness:
Expand Down Expand Up @@ -72,6 +143,8 @@ class Main_GBEVplanState extends State<MainGBEVplan> {
return DynamicColorBuilder(
builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
return MaterialApp(
navigatorKey: navigatorKey,

title: 'Flutter Demo',
theme: ThemeData(
useMaterial3: true,
Expand All @@ -98,7 +171,8 @@ class Main_GBEVplanState extends State<MainGBEVplan> {
'/home': (context) => const Home(),
'/home/settings': (context) => const HomeSettings(),
'/home/news': (context) => const HomeNews(),
'/home/ogtt': (context) => const HomeOGTimeTable()
'/home/ogtt': (context) => const HomeOGTimeTable(),
'/PAGE_TEST': (context) => const PAGE_TEST(),
},
);
});
Expand Down
6 changes: 1 addition & 5 deletions gbevplan/lib/pages/login.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,8 @@ class page_login extends StatefulWidget {

// ignore: camel_case_types
class _page_loginState extends State<page_login> {
@override
void initState() {
super.initState();
}

bool _remmevalue = false;

@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
Expand Down
16 changes: 16 additions & 0 deletions gbevplan/lib/pages/test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import 'package:flutter/material.dart';

class PAGE_TEST extends StatelessWidget {
const PAGE_TEST({super.key});

@override
Widget build(BuildContext context) {
final BUILDmessage = ModalRoute.of(context)?.settings.arguments;

return Scaffold(
body: Center(
child: Text(BUILDmessage != null ? BUILDmessage.toString() : ""),
),
);
}
}
4 changes: 4 additions & 0 deletions gbevplan/linux/flutter/generated_plugin_registrant.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@

#include "generated_plugin_registrant.h"

#include <awesome_notifications/awesome_notifications_plugin.h>
#include <dynamic_color/dynamic_color_plugin.h>

void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) awesome_notifications_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "AwesomeNotificationsPlugin");
awesome_notifications_plugin_register_with_registrar(awesome_notifications_registrar);
g_autoptr(FlPluginRegistrar) dynamic_color_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "DynamicColorPlugin");
dynamic_color_plugin_register_with_registrar(dynamic_color_registrar);
Expand Down
1 change: 1 addition & 0 deletions gbevplan/linux/flutter/generated_plugins.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#

list(APPEND FLUTTER_PLUGIN_LIST
awesome_notifications
dynamic_color
)

Expand Down
4 changes: 4 additions & 0 deletions gbevplan/macos/Flutter/GeneratedPluginRegistrant.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,22 @@
import FlutterMacOS
import Foundation

import awesome_notifications
import cloud_functions
import device_info_plus
import dynamic_color
import firebase_core
import firebase_database
import firebase_messaging
import path_provider_foundation

func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AwesomeNotificationsPlugin.register(with: registry.registrar(forPlugin: "AwesomeNotificationsPlugin"))
FLTFirebaseFunctionsPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseFunctionsPlugin"))
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
DynamicColorPlugin.register(with: registry.registrar(forPlugin: "DynamicColorPlugin"))
FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin"))
FLTFirebaseDatabasePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseDatabasePlugin"))
FLTFirebaseMessagingPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseMessagingPlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
}
40 changes: 40 additions & 0 deletions gbevplan/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.11.0"
awesome_notifications:
dependency: "direct main"
description:
name: awesome_notifications
sha256: d9e46ce7f5171ee1e9b1c5bc6dc40bd77528561f592842ce97ce3a0a9ae155ef
url: "https://pub.dev"
source: hosted
version: "0.9.3+1"
boolean_selector:
dependency: transitive
description:
Expand Down Expand Up @@ -185,6 +193,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.2.5+9"
firebase_messaging:
dependency: "direct main"
description:
name: firebase_messaging
sha256: "2d0ea2234ce46030eda2e6922611115ce603adc614ebd8c00e7db06a8929efbb"
url: "https://pub.dev"
source: hosted
version: "15.0.1"
firebase_messaging_platform_interface:
dependency: transitive
description:
name: firebase_messaging_platform_interface
sha256: c38c27f58cb6a88b8c145018d0567802376549c32a60098a13f3bdf3ddea326f
url: "https://pub.dev"
source: hosted
version: "4.5.39"
firebase_messaging_web:
dependency: transitive
description:
name: firebase_messaging_web
sha256: "8502849c2f232f7db338c052e045442207a0db82bd03ff14be3c80897dd8c26c"
url: "https://pub.dev"
source: hosted
version: "3.8.9"
flutter:
dependency: "direct main"
description: flutter
Expand Down Expand Up @@ -232,6 +264,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.0.2"
intl:
dependency: transitive
description:
name: intl
sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf
url: "https://pub.dev"
source: hosted
version: "0.19.0"
leak_tracker:
dependency: transitive
description:
Expand Down
Loading

0 comments on commit f01f599

Please sign in to comment.