Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/mobile/notif sending #147

Merged
merged 2 commits into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions frontend/occupi-mobile4/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ web-build/

eas.json
app.json
occupi-4d02a-firebase-adminsdk-4ea8s-545f5460aa.json
google-services.json

# macOS
.DS_Store
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Empty file.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#Thu Jul 04 00:58:00 SAST 2024
gradle.version=8.1.1
Binary file not shown.
Empty file.
3 changes: 2 additions & 1 deletion frontend/occupi-mobile4/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"foregroundImage": "./assets/images/adaptive-icon.png",
"backgroundColor": "#ffffff"
},
"package": "com.y2kodedev.occupi"
"package": "com.y2kodedev.occupi",
"googleServicesFile": "./google-services.json"
},
"web": {
"bundler": "metro",
Expand Down
1 change: 1 addition & 0 deletions frontend/occupi-mobile4/app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export default function RootLayout() {
<Stack.Screen name="viewbookingdetails" options={{ headerShown: false }} />
<Stack.Screen name="faqpage" options={{ headerShown: false }} />
<Stack.Screen name="set-notifications" options={{ headerShown: false }} />
<Stack.Screen name="notiftester" options={{ headerShown: false }} />
</Stack>
</GluestackUIProvider>
);
Expand Down
22 changes: 22 additions & 0 deletions frontend/occupi-mobile4/app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
plugins {
id("com.android.application")

// Add the Google services Gradle plugin
id("com.google.gms.google-services")

...
}

dependencies {
// Import the Firebase BoM
implementation(platform("com.google.firebase:firebase-bom:33.1.1"))


// TODO: Add the dependencies for Firebase products you want to use
// When using the BoM, don't specify versions in Firebase dependencies
implementation("com.google.firebase:firebase-analytics")


// Add the dependencies for any other desired Firebase products
// https://firebase.google.com/docs/android/setup#available-libraries
}
7 changes: 7 additions & 0 deletions frontend/occupi-mobile4/app/notiftester.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import NotifTester from "../screens/Settings/NotifTester";

export default function Home() {
return (
<NotifTester />
);
}
7 changes: 7 additions & 0 deletions frontend/occupi-mobile4/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
plugins {
// ...

// Add the dependency for the Google services Gradle plugin
id("com.google.gms.google-services") version "4.4.2" apply false

}
34 changes: 34 additions & 0 deletions frontend/occupi-mobile4/package-lock.json

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

3 changes: 2 additions & 1 deletion frontend/occupi-mobile4/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@
"react-native-svg": "^15.3.0",
"react-native-web": "~0.19.10",
"zod": "^3.23.8",
"expo-notifications": "~0.28.9"
"expo-notifications": "~0.28.9",
"expo-device": "~6.0.2"
},
"devDependencies": {
"@babel/core": "^7.20.0",
Expand Down
2 changes: 1 addition & 1 deletion frontend/occupi-mobile4/screens/Login/SplashScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export default function SplashScreen() {
useEffect(() => {
const timer = setTimeout(() => {
setSelectedIndex(1); // Assuming Onboarding1 is at index 1
router.replace('/settings'); // Navigate to Onboarding1 screen
router.replace('/notiftester'); // Navigate to Onboarding1 screen
}, 5000); // 8 seconds

return () => clearTimeout(timer); // Clean up timer on component unmount
Expand Down
131 changes: 131 additions & 0 deletions frontend/occupi-mobile4/screens/Settings/NotifTester.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { useState, useEffect, useRef } from 'react';
import { Text, View, Button, Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';


Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});



async function sendPushNotification(expoPushToken: string) {
const message = {
to: expoPushToken,
sound: 'default',
title: 'Original Title',
body: 'And here is the body!',
data: { someData: 'goes here' },
};

await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
});
}


function handleRegistrationError(errorMessage: string) {
alert(errorMessage);
throw new Error(errorMessage);
}

async function registerForPushNotificationsAsync() {
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}

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;
console.log(pushTokenString);
return pushTokenString;
} catch (e: unknown) {
handleRegistrationError(`${e}`);
}
} else {
handleRegistrationError('Must use physical device for push notifications');
}
}

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

useEffect(() => {
registerForPushNotificationsAsync()
.then(token => setExpoPushToken(token ?? ''))
.catch((error: any) => setExpoPushToken(`${error}`));

notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
setNotification(notification);
});

responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
console.log(response);
});

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

return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}>
<Text>Your Expo push token: {expoPushToken}</Text>
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text>Title: {notification && notification.request.content.title} </Text>
<Text>Body: {notification && notification.request.content.body}</Text>
<Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
</View>
<Button
title="Press to Send Notification"
onPress={async () => {
await sendPushNotification(expoPushToken);
}}
/>
</View>
);
}
2 changes: 2 additions & 0 deletions occupi-backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ require (
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
)

require github.com/oliveroneill/exponent-server-sdk-golang v0.0.0-20210823140141-d050598be512 // indirect

require (
github.com/aymerick/douceur v0.2.0 // indirect
github.com/bytedance/sonic v1.11.7 // indirect
Expand Down
2 changes: 2 additions & 0 deletions occupi-backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/oliveroneill/exponent-server-sdk-golang v0.0.0-20210823140141-d050598be512 h1:/ZSmjwl1inqsiHMhn+sPlEtSHdVTf+TH3LNGGdMQ/vA=
github.com/oliveroneill/exponent-server-sdk-golang v0.0.0-20210823140141-d050598be512/go.mod h1:Isv/48UnAjtxS8FD80Bito3ZJqZRyIMxKARIEITfW4k=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
Expand Down
39 changes: 39 additions & 0 deletions occupi-backend/notifications/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package main

import (
"fmt"
expo "github.com/oliveroneill/exponent-server-sdk-golang/sdk"
)

func main() {
// To check the token is valid
pushToken, err := expo.NewExponentPushToken("ExponentPushToken[5cpRYINQu42bhcKM5b7Vsb]")
if err != nil {
panic(err)
}

// Create a new Expo SDK client
client := expo.NewPushClient(nil)

// Publish message
response, err := client.Publish(
&expo.PushMessage{
To: []expo.ExponentPushToken{pushToken},
Body: "This is a test notification",
Data: map[string]string{"withSome": "data"},
Sound: "default",
Title: "Notification Title",
Priority: expo.DefaultPriority,
},
)

// Check errors
if err != nil {
panic(err)
}

// Validate responses
if response.ValidateResponse() != nil {
fmt.Println(response.PushMessage.To, "failed")
}
}
Loading