Skip to content

Commit

Permalink
Fixed notifications (probably)
Browse files Browse the repository at this point in the history
  • Loading branch information
StarNumber12046 committed Sep 16, 2024
1 parent 67e0e25 commit ffd78ae
Show file tree
Hide file tree
Showing 6 changed files with 1,630 additions and 92 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ jobs:
- name: 🔒 Decode google-services.json
run: |
echo "${{ secrets.ENCODED_GOOGLE_SERVICES }}" | base64 --decode > google-services.json
echo "${{ secrets.ENCODED_CREDS }}" | base64 --decode > creds.ts
ls -la
- uses: mskelton/setup-yarn@v1
Expand Down
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,8 @@ web-build/
# The following patterns were generated by expo-cli

expo-env.d.ts
# @end expo-cli
# @end expo-cli

credentials.json
google-services.json
creds.ts
14 changes: 13 additions & 1 deletion app.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default {
foregroundImage: "./assets/images/adaptive-icon.png",
backgroundColor: "#000000",
},
googleServicesFile: process.env.GOOGLE_SERVICES_JSON,
googleServicesFile: "android/app/google-services.json",
package: "com.rebeal",
},
web: {
Expand All @@ -39,6 +39,18 @@ export default {
sounds: ["./assets/sounds/notification.wav"],
},
],
"@react-native-firebase/app",
"@react-native-firebase/messaging",
[
"expo-build-properties",
{
ios: {
buildProperties: {
"app.build.version": `1.0.0`,
},
},
},
],
],
experiments: {
typedRoutes: true,
Expand Down
131 changes: 61 additions & 70 deletions app/onboarding.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import { useState, useEffect, useRef } from "react";
import {
Text,
View,
Button,
Platform,
Pressable,
StyleSheet,
} from "react-native";
import * as Device from "expo-device";
import messaging, {
firebase,
FirebaseMessagingTypes,
} from "@react-native-firebase/messaging";
import { Text, View, Pressable, StyleSheet } from "react-native";
import * as Notifications from "expo-notifications";
import Constants from "expo-constants";
import { router } from "expo-router";
import firebaseConfig from "@/creds";

if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
} else {
firebase.app(); // Use the existing app if already initialized
}
// Initialize Firebase only if it's not initialized

Notifications.setNotificationHandler({
handleNotification: async () => ({
Expand All @@ -26,95 +29,82 @@ function handleRegistrationError(errorMessage: string) {
throw new Error(errorMessage);
}

// Request user permission and get FCM token
async function registerForPushNotificationsAsync() {
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
sound: "notification.wav",
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;

if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
handleRegistrationError(
"Permission not granted to get push token for push notification!"
);
return;
}
const projectId =
Constants?.expoConfig?.extra?.eas?.projectId ??
Constants?.easConfig?.projectId;
if (!projectId) {
handleRegistrationError("Project ID not found");
}
try {
const pushTokenString = (
await Notifications.getExpoPushTokenAsync({
projectId,
})
).data;
if (enabled) {
console.log("Authorization status:", authStatus);

try {
const pushTokenString = await messaging().getToken();
return pushTokenString;
} catch (e: unknown) {
handleRegistrationError(`${e}`);
handleRegistrationError(`FCM token retrieval failed: ${e}`);
}
} else {
handleRegistrationError("Must use physical device for push notifications");
handleRegistrationError("Permission not granted for FCM");
}
}

export default function Onboarding() {
const [expoPushToken, setExpoPushToken] = useState("");
const [notification, setNotification] = useState<
Notifications.Notification | undefined
FirebaseMessagingTypes.RemoteMessage | undefined
>(undefined);
const notificationListener = useRef<Notifications.Subscription>();
const responseListener = useRef<Notifications.Subscription>();

useEffect(() => {
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
const unsubscribeOnMessage = messaging().onMessage(
async (remoteMessage) => {
setNotification(remoteMessage);
console.log(
"A new FCM message arrived!",
JSON.stringify(remoteMessage)
);
}
);

const unsubscribeOnNotificationOpenedApp =
messaging().onNotificationOpenedApp((remoteMessage) => {
console.log(
"Notification caused app to open from background state:",
remoteMessage
);
});

responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
console.log(response);
messaging()
.getInitialNotification()
.then((remoteMessage) => {
if (remoteMessage) {
console.log(
"Notification caused app to open from quit state:",
remoteMessage
);
}
});

return () => {
notificationListener.current &&
Notifications.removeNotificationSubscription(
notificationListener.current
);
responseListener.current &&
Notifications.removeNotificationSubscription(responseListener.current);
unsubscribeOnMessage();
unsubscribeOnNotificationOpenedApp();
};
}, []);

async function onClick() {
const pushTokenString = await registerForPushNotificationsAsync();
const body = { expoToken: pushTokenString, region: "europe-west" };
const body = { fcmToken: pushTokenString, region: "europe-west" };

const res = await fetch("https://rebeal-server.vercel.app/register", {
// @ts-ignore
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});

console.log(await res.text());
console.log(pushTokenString);
setExpoPushToken(pushTokenString ?? "");
router.navigate("/");
}
Expand All @@ -130,7 +120,7 @@ export default function Onboarding() {
}}
>
<Text style={{ fontWeight: "bold", color: "white", fontSize: 28 }}>
Enable notificaations
Enable notifications
</Text>
<Text style={{ color: "#ffffff90", fontSize: 18 }}>
And receive your daily dose of real life
Expand All @@ -147,13 +137,14 @@ export default function Onboarding() {
</View>
);
}

const styles = StyleSheet.create({
button: {
backgroundColor: "white",
width: "90%",
color: "black",
justifyContent: "center", // Center vertically
alignItems: "center", // Center horizontally
justifyContent: "center",
alignItems: "center",
position: "absolute",
padding: 15,
bottom: 100,
Expand All @@ -166,8 +157,8 @@ const styles = StyleSheet.create({
borderColor: "white",
borderWidth: 2,
width: "90%",
justifyContent: "center", // Center vertically
alignItems: "center", // Center horizontally
justifyContent: "center",
alignItems: "center",
position: "absolute",
padding: 15,
fontSize: 18,
Expand Down
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,30 @@
"@expo-google-fonts/inter": "^0.2.3",
"@expo/vector-icons": "^14.0.2",
"@react-native-async-storage/async-storage": "1.23.1",
"@react-native-firebase/app": "^20.5.0",
"@react-native-firebase/messaging": "^20.5.0",
"@react-navigation/native": "^6.0.2",
"@types/intl": "^1.2.2",
"country-codes-flags-phone-codes": "^1.1.1",
"date-fns": "^3.6.0",
"dayjs": "^1.11.13",
"expo": "~51.0.28",
"expo-build-properties": "~0.12.5",
"expo-camera": "~15.0.16",
"expo-constants": "^16.0.2",
"expo-device": "^6.0.2",
"expo-font": "~12.0.9",
"expo-haptics": "^13.0.1",
"expo-image-manipulator": "^12.0.5",
"expo-linking": "~6.3.1",
"expo-notifications": "^0.28.16",
"expo-notifications": "~0.28.16",
"expo-router": "~3.5.23",
"expo-splash-screen": "~0.27.5",
"expo-status-bar": "~1.12.1",
"expo-system-ui": "~3.0.7",
"expo-web-browser": "~13.0.3",
"firebase": "^10.13.1",
"firebase-admin": "^12.5.0",
"happy-headers": "^1.5.0",
"intl": "^1.2.5",
"intl-relative-time-format": "^1.0.7",
Expand Down
Loading

0 comments on commit ffd78ae

Please sign in to comment.