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

integrated notifications #232

Closed
wants to merge 5 commits into from
Closed
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
19 changes: 16 additions & 3 deletions apps/mobile/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,18 @@
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.INTERNET",
"android.permission.RECORD_AUDIO",
"android.permission.CAMERA"
"android.permission.CAMERA",
"NOTIFICATIONS"
]
},
"web": {
"favicon": "./assets/favicon.png",
"deepLinking": true,
"bundler": "metro"
"bundler": "metro",
"fonts": [
{
"asset": "./assets/fonts/PublicPixel-z84yD.ttf"
}
]
},
"plugins": [
[
Expand Down Expand Up @@ -88,6 +93,14 @@
"merchantIdentifier": "",
"enableGooglePay": true
}
],
[
"expo-notifications",
{
"icon": "./assets/notification-icon.png",
"color": "#ffffff",
"sounds": ["./assets/notification-sound.wav"]
}
]
],
"sdkVersion": "51.0.0",
Expand Down
3 changes: 1 addition & 2 deletions apps/mobile/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@ import registerRootComponent from 'expo/build/launch/registerRootComponent';
import {Wrapper} from './src/app/Wrapper';

registerRootComponent(Wrapper);

AppRegistry.registerComponent(appName, () => App);
AppRegistry.registerComponent(appName, () => App);
8 changes: 4 additions & 4 deletions apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"@dynamic-labs/client": "4.0.0-alpha.8",
"@dynamic-labs/react-hooks": "4.0.0-alpha.8",
"@dynamic-labs/react-native-extension": "4.0.0-alpha.8",
"@dynamic-labs/utils": "^3.3.0",
"@dynamic-labs/utils": "4.0.0-alpha.8",
"@dynamic-labs/viem-extension": "4.0.0-alpha.8",
"@expo/metro-runtime": "~3.2.1",
"@getalby/bitcoin-connect-react": "^3.5.3",
Expand All @@ -45,7 +45,7 @@
"@nostr-dev-kit/ndk": "2.10.1",
"@nostr-dev-kit/ndk-wallet": "^0.2.0",
"@rainbow-me/rainbowkit": "^2.1.5",
"@react-native-async-storage/async-storage": "^1.24.0",
"@react-native-async-storage/async-storage": "1.23.1",
"@react-native-community/netinfo": "11.3.1",
"@react-native-picker/picker": "2.7.5",
"@react-navigation/bottom-tabs": "^6.5.20",
Expand All @@ -72,7 +72,7 @@
"common": "workspace:*",
"crypto-es": "^2.1.0",
"events": "^3.3.0",
"expo": "~51.0.28",
"expo": "~51.0.38",
"expo-application": "^5.9.1",
"expo-auth-session": "^5.5.2",
"expo-av": "~14.0.7",
Expand Down Expand Up @@ -127,7 +127,7 @@
"viem": "2.x",
"wagmi": "^2.12.8",
"zustand": "^4.5.2",
"@stripe/stripe-react-native":"0.38.6"
"@stripe/stripe-react-native": "0.37.2"
},
"devDependencies": {
"@babel/core": "^7.20.0",
Expand Down
55 changes: 11 additions & 44 deletions apps/mobile/src/app/App.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import '@walletconnect/react-native-compat';

import {starknetChainId, useAccount} from '@starknet-react/core';
import * as Font from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';
import {useCallback, useEffect, useState} from 'react';
import {View} from 'react-native';

import {Platform, View} from 'react-native';
import {registerForPushNotificationsAsync} from '../services/notifications';
import {useTips} from '../hooks';
import {useDialog, useToast} from '../hooks/modals';
import {Router} from './Router';
Expand All @@ -15,7 +14,6 @@ SplashScreen.preventAutoHideAsync();
export default function App() {
const [appIsReady, setAppIsReady] = useState(false);
const [sentTipNotification, setSentTipNotification] = useState(false);

const tips = useTips();
const {showToast} = useToast();

Expand All @@ -38,48 +36,17 @@ export default function App() {
})();
}, []);

const {showDialog, hideDialog} = useDialog();

const account = useAccount();

useEffect(() => {
const chainId = account.chainId ? starknetChainId(account.chainId) : undefined;

if (chainId) {
// if (chainId !== CHAIN_ID) {
// showDialog({
// title: 'Wrong Network',
// description:
// 'AFK currently only supports the Starknet Sepolia network. Please switch to the Sepolia network to continue.',
// buttons: [],
// });
// } else {
// hideDialog();
// }
if (Platform.OS !== 'web') {
registerForPushNotificationsAsync()
.then((token: string | null) => {
if (token) {
console.log('Push token:', token);
}
})
.catch((error: Error) => console.error('Failed to get push token:', error));
}

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [account.chainId]);

useEffect(() => {
const interval = setInterval(() => tips.refetch(), 2 * 60 * 1_000);
return () => clearInterval(interval);
}, [tips]);

useEffect(() => {
if (sentTipNotification) return;

const hasUnclaimedTip = (tips.data ?? []).some((tip) => !tip.claimed && tip.depositId);
if (hasUnclaimedTip) {
setSentTipNotification(true);
showToast({
type: 'info',
title: 'You have unclaimed tips',
});
}

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tips.data]);
}, []);

const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
Expand Down
14 changes: 12 additions & 2 deletions apps/mobile/src/components/PrivateMessages/Chat/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {FlatList, Image, Text, View} from 'react-native';

import {useStyles} from '../../../hooks';
import {useToast} from '../../../hooks/modals';
import {sendNotificationForEvent} from '../../../utils/notifications';
import {IconButton} from '../../IconButton';
import {MessageInput} from '../PrivateMessageInput';
import stylesheet from './styles';
Expand Down Expand Up @@ -51,11 +52,20 @@ export const Chat: React.FC<ChatProps> = ({item, handleGoBack, user}) => {
receiverPublicKeyProps: receiverPublicKey,
},
{
onSuccess: () => {
// showToast({title: 'Message sent', type: 'success'});
onSuccess: async () => {
queryClient.invalidateQueries({
queryKey: ['messagesSent'],
});

try {
await sendNotificationForEvent(receiverPublicKey, 'privateMessage', {
senderName: user?.name || 'Someone',
conversationId: item.id.toString(),
authorName: message.substring(0, 50) + (message.length > 50 ? '...' : ''),
});
} catch (error) {
console.error('Failed to send notification:', error);
}
},
onError() {
showToast({title: 'Error sending message', type: 'error'});
Expand Down
2 changes: 1 addition & 1 deletion apps/mobile/src/components/TabSelector/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const TabSelector: React.FC<ITabSelector> = ({
key={i}
style={[
tabStyle ?? styles.tab,
activeTab === b?.tab ? activeTabStyle ?? styles.active : null,
activeTab === b?.tab ? (activeTabStyle ?? styles.active) : null,
]}
onPress={() => handlePress(b?.tab, b?.screen)}
>
Expand Down
8 changes: 4 additions & 4 deletions apps/mobile/src/hooks/launchpad/useCreateToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export type DeployTokenFormValues = {
export const useCreateToken = () => {
const deployToken = async (account: AccountInterface, data: DeployTokenFormValues) => {
const CONTRACT_ADDRESS_SALT_DEFAULT =
data?.contract_address_salt ??
(await account?.getChainId()) == constants.StarknetChainId.SN_MAIN
(data?.contract_address_salt ??
(await account?.getChainId()) == constants.StarknetChainId.SN_MAIN)
? '0x36d8be2991d685af817ef9d127ffb00fbb98a88d910195b04ec4559289a99f6'
: '0x36d8be2991d685af817ef9d127ffb00fbb98a88d910195b04ec4559289a99f6';

Expand Down Expand Up @@ -51,8 +51,8 @@ export const useCreateToken = () => {

const deployTokenAndLaunch = async (account: AccountInterface, data: DeployTokenFormValues) => {
const CONTRACT_ADDRESS_SALT_DEFAULT =
data?.contract_address_salt ??
(await account?.getChainId()) == constants.StarknetChainId.SN_MAIN
(data?.contract_address_salt ??
(await account?.getChainId()) == constants.StarknetChainId.SN_MAIN)
? '0x36d8be2991d685af817ef9d127ffb00fbb98a88d910195b04ec4559289a99f6'
: '0x36d8be2991d685af817ef9d127ffb00fbb98a88d910195b04ec4559289a99f6';

Expand Down
4 changes: 2 additions & 2 deletions apps/mobile/src/modules/Lightning/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,8 @@ export const LightningNetworkWallet = () => {
{isLoading
? 'Connecting...'
: isExtensionAvailable
? 'Connect with Alby Extension'
: 'Connect with Alby NWC'}
? 'Connect with Alby Extension'
: 'Connect with Alby NWC'}
</Text>
</Button>
</View>
Expand Down
2 changes: 1 addition & 1 deletion apps/mobile/src/modules/PostCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const PostCard: React.FC<PostCardProps> = ({event, isRepostProps, isBookm

let repostedEvent = undefined;
const [isRepost, setIsRepost] = useState(
isRepostProps ?? event?.kind == NDKKind.Repost ? true : false,
(isRepostProps ?? event?.kind == NDKKind.Repost) ? true : false,
);

if (event?.kind == NDKKind.Repost) {
Expand Down
2 changes: 1 addition & 1 deletion apps/mobile/src/modules/VideoPostCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const VideoPostCard: React.FC<PostCardProps> = ({event, isRepostProps, is

let repostedEvent = undefined;
const [isRepost, setIsRepost] = useState(
isRepostProps ?? event?.kind == NDKKind.Repost ? true : false,
(isRepostProps ?? event?.kind == NDKKind.Repost) ? true : false,
);

if (event?.kind == NDKKind.Repost) {
Expand Down
4 changes: 2 additions & 2 deletions apps/mobile/src/modules/WalletModal/walletUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ export function injectedWithFallback() {
return !window.ethereum
? 'Install MetaMask'
: window.ethereum?.isMetaMask
? 'MetaMask'
: 'Browser Wallet';
? 'MetaMask'
: 'Browser Wallet';
},
};
});
Expand Down
19 changes: 19 additions & 0 deletions apps/mobile/src/serviceWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
self.addEventListener('push', event => {
const options = {
body: event.data.text(),
icon: '/notification-icon.png',
badge: '/badge-icon.png',
vibrate: [200, 100, 200]
};

event.waitUntil(
self.registration.showNotification('AFK Community', options)
);
});

self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil(
clients.openWindow('/')
);
});
21 changes: 21 additions & 0 deletions apps/mobile/src/services/notifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export type NotificationData = {
type: 'tip' | 'privateMessage' | 'tokenLaunch' | 'note' | 'tokenLiquidity';
data: {
amount?: string;
token?: string;
senderName?: string;
tokenName?: string;
action?: string;
authorName?: string;
conversationId?: string;
coinAddress?: string;
noteId?: string;
liquidityAmount?: string;
message?: string;
};
};

export const registerForPushNotificationsAsync = async () => {
// Implementation here
return null;
};
2 changes: 2 additions & 0 deletions apps/mobile/src/services/notifications/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Add your handler-related code here
export {};
5 changes: 5 additions & 0 deletions apps/mobile/src/services/notifications/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

export * from './pushNotification';
export * from './registration';
export * from './types';
export * from './webNotifications';
24 changes: 24 additions & 0 deletions apps/mobile/src/services/notifications/pushNotification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import {NotificationData} from './types';

export async function sendPushNotification(
expoPushToken: string,
title: string,
body: string,
data?: NotificationData,
) {
const message = {
to: expoPushToken,
sound: 'default',
title,
body,
data: data || {},
};

await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
});
}
35 changes: 35 additions & 0 deletions apps/mobile/src/services/notifications/registration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import Constants from 'expo-constants';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import {Platform} from 'react-native';

export async function registerForPushNotificationsAsync() {
if (Platform.OS === 'web') return null;

if (!Device.isDevice) return null;

const {status: existingStatus} = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;

if (existingStatus !== 'granted') {
const {status} = await Notifications.requestPermissionsAsync();
finalStatus = status;
}

if (finalStatus !== 'granted') return null;

const token = await Notifications.getExpoPushTokenAsync({
projectId: Constants.expoConfig?.extra?.eas?.projectId,
});

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

return token.data;
}
15 changes: 15 additions & 0 deletions apps/mobile/src/services/notifications/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export type NotificationData = {
type: 'tip' | 'privateMessage' | 'tokenLaunch' | 'note' | 'tokenLiquidity';
data: {
amount?: string;
token?: string;
senderName?: string;
tokenName?: string;
action?: string;
authorName?: string;
conversationId?: string;
coinAddress?: string;
noteId?: string;
liquidityAmount?: string;
};
};
Loading