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: add push notifications #163

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
5 changes: 5 additions & 0 deletions app/(app)/notifications.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Notifications } from "../../pages/Notifications";

export default function Page() {
return <Notifications />;
}
3 changes: 3 additions & 0 deletions components/Icons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ArchiveRestore,
ArrowDown,
ArrowLeftRight,
Bell,
Bitcoin,
BookUser,
Camera,
Expand Down Expand Up @@ -95,12 +96,14 @@ interopIcon(CircleCheck);
interopIcon(TriangleAlert);
interopIcon(LogOut);
interopIcon(ArchiveRestore);
interopIcon(Bell);

export {
AlertCircle,
ArchiveRestore,
ArrowDown,
ArrowLeftRight,
Bell,
Bitcoin,
BookUser,
Camera,
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@
"expo-camera": "~15.0.16",
"expo-clipboard": "~6.0.3",
"expo-constants": "~16.0.2",
"expo-device": "~6.0.2",
"expo-font": "~12.0.10",
"expo-linear-gradient": "~13.0.2",
"expo-linking": "~6.3.1",
"expo-local-authentication": "~14.0.1",
"expo-notifications": "~0.28.19",
"expo-router": "^3.5.23",
"expo-secure-store": "^13.0.2",
"expo-status-bar": "~1.12.1",
Expand Down
194 changes: 194 additions & 0 deletions pages/Notifications.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import Constants from "expo-constants";
import React, { useEffect, useRef, useState } from "react";
import { Platform, View } from "react-native";
import Screen from "~/components/Screen";
import { Button } from "~/components/ui/button";
import { Text } from "~/components/ui/text";

import { Nip47Notification } from "@getalby/sdk/dist/NWCClient";
import * as Device from "expo-device";
import * as ExpoNotifications from "expo-notifications";
import { useAppStore } from "~/lib/state/appStore";


ExpoNotifications.setNotificationHandler({
handleNotification: async (notification) => {
console.log("🔔 handleNotification", { data: notification.request.content.data })

Check failure on line 16 in pages/Notifications.tsx

View workflow job for this annotation

GitHub Actions / linting

Unexpected console statement

if (!notification.request.content.data.isLocal) {
console.log("🏠️ Local notification", notification.request.content);

Check failure on line 19 in pages/Notifications.tsx

View workflow job for this annotation

GitHub Actions / linting

Unexpected console statement

const encryptedData = notification.request.content.data.content;
const nwcClient = useAppStore.getState().nwcClient!;

try {
console.log("🔴", encryptedData, nwcClient?.secret);

Check failure on line 25 in pages/Notifications.tsx

View workflow job for this annotation

GitHub Actions / linting

Unexpected console statement
const decryptedContent = await nwcClient.decrypt(
nwcClient?.walletPubkey!,
encryptedData,
);
console.log("🔓️ decrypted data", decryptedContent);

Check failure on line 30 in pages/Notifications.tsx

View workflow job for this annotation

GitHub Actions / linting

Unexpected console statement
const nip47Notification = JSON.parse(decryptedContent) as Nip47Notification;
console.log("deserialized", nip47Notification);

Check failure on line 32 in pages/Notifications.tsx

View workflow job for this annotation

GitHub Actions / linting

Unexpected console statement

if (nip47Notification.notification_type === "payment_received") {
ExpoNotifications.scheduleNotificationAsync({
content: {
title: `You just received ${Math.floor(nip47Notification.notification.amount / 1000)} sats`,
body: nip47Notification.notification.description,
data: {
...notification.request.content.data,
isLocal: true,
}
},
trigger: null
});
}



} catch (e) {
console.error("Failed to parse decrypted event content", e);
return;
}
}

return {
shouldShowAlert: !!notification.request.content.data.isLocal,
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") {
ExpoNotifications.setNotificationChannelAsync("default", {
name: "default",
importance: ExpoNotifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}

if (Device.isDevice) {
const { status: existingStatus } =
await ExpoNotifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await ExpoNotifications.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 ExpoNotifications.getExpoPushTokenAsync({
projectId,
})
).data;
return pushTokenString;
} catch (e: unknown) {
handleRegistrationError(`${e}`);
}
} else {
handleRegistrationError("Must use physical device for push notifications");
}
}

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

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

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

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

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

return (
<View
style={{ flex: 1, alignItems: "center", justifyContent: "space-around" }}
>
<Screen title="Notifications" />
<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
onPress={async () => {
await sendPushNotification(expoPushToken);
}}
>
<Text>Send push</Text>
</Button>
</View>
);
}
12 changes: 11 additions & 1 deletion pages/settings/Settings.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Link, router } from "expo-router";
import { Alert, TouchableOpacity, View } from "react-native";
import {
Bell,
Bitcoin,
Egg,
Fingerprint,
Expand Down Expand Up @@ -104,7 +105,16 @@ export function Settings() {
}}
>
<Egg className="text-foreground" />
<Text className="font-medium2 text-xl">Open Onboarding</Text>
<Text className="font-medium2 text-xl">Onboarding</Text>
</TouchableOpacity>
<TouchableOpacity
className="flex flex-row gap-4"
onPress={() => {
router.push("/notifications");
}}
>
<Bell className="text-foreground" />
<Text className="font-medium2 text-xl">Notifications</Text>
</TouchableOpacity>
<TouchableOpacity
className="flex flex-row gap-4"
Expand Down
Loading
Loading