Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeljscript committed Oct 8, 2024
1 parent e5b2623 commit 5ca0641
Show file tree
Hide file tree
Showing 12 changed files with 69 additions and 129 deletions.
1 change: 1 addition & 0 deletions apps/wallet-mobile/.storybook/storybook.requires.js

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

3 changes: 0 additions & 3 deletions apps/wallet-mobile/src/AppNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import {
import {useDeepLinkWatcher} from './features/Links/common/useDeepLinkWatcher'
import {useNotifications} from './features/Notifications/useCases/common/hooks'
import {NotificationsDevScreen} from './features/Notifications/useCases/NotificationsDevScreen'
import {PortfolioScreen} from './features/Portfolio/useCases/PortfolioScreen'
import {SearchProvider} from './features/Search/SearchContext'
import {SetupWalletNavigator} from './features/SetupWallet/SetupWalletNavigator'
import {useHasWallets} from './features/WalletManager/common/hooks/useHasWallets'
Expand Down Expand Up @@ -206,8 +205,6 @@ export const AppNavigator = () => {

<Stack.Screen name="playground" component={Playground} />

<Stack.Screen name="portfolio-dashboard" component={PortfolioScreen} />

<Stack.Screen name="notifications" component={NotificationsDevScreen} />
</Stack.Group>
)}
Expand Down
6 changes: 5 additions & 1 deletion apps/wallet-mobile/src/YoroiApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import {useMigrations} from './kernel/storage/migrations/useMigrations'
import {rootStorage} from './kernel/storage/rootStorage'
import {PoolTransitionProvider} from './legacy/Staking/PoolTransition/PoolTransitionProvider'
import {useThemeStorageMaker} from './yoroi-wallets/hooks'
import {NotificationProvider} from '@yoroi/notifications'
import {notificationManager} from './features/Notifications/useCases/common/notification-manager'

enableScreens(true)
enableFreeze(true)
Expand Down Expand Up @@ -63,7 +65,9 @@ const Yoroi = () => {
<PoolTransitionProvider>
<BrowserProvider>
<AutomaticWalletOpenerProvider>
<InitApp />
<NotificationProvider manager={notificationManager}>
<InitApp />
</NotificationProvider>
</AutomaticWalletOpenerProvider>
</BrowserProvider>
</PoolTransitionProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ import {SafeAreaView} from 'react-native-safe-area-context'

import {Button} from '../../../components/Button/Button'
import {ScrollView} from '../../../components/ScrollView/ScrollView'
import {useMockedNotifications} from './common/mocks'
import {createTransactionReceivedNotification} from './common/transaction-received-notification'
import {notificationManager} from './common/notification-manager'

export const NotificationsDevScreen = () => {
const {manager} = useMockedNotifications()
const manager = notificationManager
return (
<NotificationProvider manager={manager}>
<Screen />
Expand All @@ -30,7 +30,7 @@ const Screen = () => {
const manager = useNotificationManager()

const handleOnTriggerTransactionReceived = () => {
manager.notification$.next(
manager.events.push(
createTransactionReceivedNotification({
previousTxsCounter: 0,
nextTxsCounter: 1,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import {Notification, Notifications} from '@jamsinclair/react-native-notifications'
import {useAsyncStorage} from '@yoroi/common'
import {notificationManagerMaker} from '@yoroi/notifications'
import {Notifications as NotificationTypes} from '@yoroi/types'
import * as React from 'react'
import {useEffect} from 'react'

import {displayNotificationEvent} from './notifications'
import {useTransactionReceivedNotificationSubject} from './transaction-received-notification'
import {notificationManager} from './notification-manager'
import {useTransactionReceivedNotifications} from './transaction-received-notification'

let initialized = false

Expand All @@ -21,51 +16,14 @@ const init = () => {
Notifications.events().registerNotificationReceivedBackground((notification: Notification) => {
console.log(`Notification received in background: ${notification.title} : ${notification.body}`)
})
}

export const useNotificationsManager = (options?: {
subscriptions?: NotificationTypes.ManagerMakerProps['subscriptions']
}) => {
const storage = useAsyncStorage()
const subscriptions = options?.subscriptions

const manager = React.useMemo(() => {
const eventsStorage = storage.join('events/')
const configStorage = storage.join('settings/')

return notificationManagerMaker({
eventsStorage,
configStorage,
subscriptions,
})
}, [storage, subscriptions])
notificationManager.hydrate()

React.useEffect(() => {
manager.hydrate()
return () => {
manager.destroy()
}
}, [manager])

return manager
return () => {
notificationManager.destroy()
}
}

export const useNotifications = () => {
useEffect(() => {
init()
}, [])

const transactionReceivedSubject = useTransactionReceivedNotificationSubject()

const manager = useNotificationsManager({
subscriptions: {
[NotificationTypes.Trigger.TransactionReceived]: transactionReceivedSubject,
},
})
React.useEffect(() => {
const subscription = manager.notification$.subscribe(displayNotificationEvent)
return () => {
subscription.unsubscribe()
}
}, [manager])
useEffect(() => init(), [])
useTransactionReceivedNotifications()
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import {mountAsyncStorage} from '@yoroi/common/src'
import {mountAsyncStorage} from '@yoroi/common'
import {notificationManagerMaker} from '@yoroi/notifications'
import {displayNotificationEvent} from './notifications'
import {Notifications} from '@yoroi/types'
import {transactionReceivedSubject} from './transaction-received-notification'

const appStorage = mountAsyncStorage({path: '/'})

export const notificationManager = notificationManagerMaker({
eventsStorage: appStorage.join('events/'),
configStorage: appStorage.join('settings/'),
display: displayNotificationEvent,
subscriptions: {
[Notifications.Trigger.TransactionReceived]: transactionReceivedSubject,
},
})
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const displayNotificationEvent = (notificationEvent: NotificationTypes.Ev
}
}

export const sendNotification = (title: string, body: string) => {
const sendNotification = (title: string, body: string) => {
const notification = new Notification({
title,
body,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,19 @@ import {YoroiWallet} from '../../../../yoroi-wallets/cardano/types'
import {useWalletManager} from '../../../WalletManager/context/WalletManagerProvider'
import {WalletManager, walletManager} from '../../../WalletManager/wallet-manager'
import {notificationManager} from './notification-manager'
import {displayNotificationEvent} from './notifications'

const BACKGROUND_FETCH_TASK = 'yoroi-notifications-background-fetch'
if (!TaskManager.isTaskDefined(BACKGROUND_FETCH_TASK)) {
const appStorage = mountAsyncStorage({path: '/'})

TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
const now = Date.now()
console.log(`Got background fetch call at date: ${new Date(now).toISOString()}`)

await syncAllWallets(walletManager)
await checkForNewTransactions(walletManager, appStorage)

// TODO: Be sure to return the correct result type!
return BackgroundFetch.BackgroundFetchResult.NewData
const notifications = await checkForNewTransactions(walletManager, appStorage)
notifications.forEach((notification) => notificationManager.events.push(notification))
const hasNewData = notifications.length > 0
return hasNewData ? BackgroundFetch.BackgroundFetchResult.NewData : BackgroundFetch.BackgroundFetchResult.NoData
})
}

// 2. Register the task at some point in your app by providing the same name,
// and some configuration options for how the background fetch should behave
// Note: This does NOT need to be in the global scope and CAN be used in your React components!
export async function registerBackgroundFetchAsync() {
return BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
minimumInterval: 60 * 10, // 10 minutes
Expand Down Expand Up @@ -61,38 +53,41 @@ const syncAllWallets = async (walletManager: WalletManager) => {
export const checkForNewTransactions = async (walletManager: WalletManager, appStorage: App.Storage) => {
const walletIds = [...walletManager.walletMetas.keys()]
const notificationsAsyncStorage = appStorage.join('notifications-transaction-received-subject/')
const notifications: NotificationTypes.TransactionReceivedEvent[] = []

for (const id of walletIds) {
const wallet = walletManager.getWalletById(id)
if (!wallet) return
if (!wallet) continue
const processed = (await notificationsAsyncStorage.getItem<string[]>(id)) || []
const txIds = getTxIds(wallet)

// TODO: Improve this
if (processed.length === 0) {
console.log(`Wallet ${id} has no processed tx ids`)
await notificationsAsyncStorage.setItem(id, txIds)
return
continue
}

const newTxIds = txIds.filter((txId) => !processed.includes(txId))

if (newTxIds.length === 0) {
console.log(`Wallet ${id} has no new tx ids on network ${wallet.networkManager.network}`)
return
continue
}
console.log('new tx ids', newTxIds)
await notificationsAsyncStorage.setItem(id, [...processed, ...newTxIds])

newTxIds.forEach((id) => {
const metadata: NotificationTypes.TransactionReceivedEvent['metadata'] = {
txId: id,
isSentByUser: false,
nextTxsCounter: 1,
previousTxsCounter: 0,
}
const notification = createTransactionReceivedNotification(metadata)
notificationManager.events.save(notification)
displayNotificationEvent(notification)
notifications.push(createTransactionReceivedNotification(metadata))
})
}

return notifications
}

const getTxIds = (wallet: YoroiWallet) => {
Expand All @@ -112,10 +107,11 @@ export const createTransactionReceivedNotification = (
} as const
}

export const useTransactionReceivedNotificationSubject = () => {
export const transactionReceivedSubject = new Subject<NotificationTypes.TransactionReceivedEvent>()

export const useTransactionReceivedNotifications = () => {
const {walletManager} = useWalletManager()
const asyncStorage = useAsyncStorage()
const [transactionReceivedSubject] = React.useState(new Subject<NotificationTypes.TransactionReceivedEvent>())

React.useEffect(() => {
registerBackgroundFetchAsync()
Expand All @@ -131,7 +127,8 @@ export const useTransactionReceivedNotificationSubject = () => {
const areAllDone = walletsDoneSyncing.length === walletInfos.length
if (!areAllDone) return

await checkForNewTransactions(walletManager, asyncStorage)
const notifications = await checkForNewTransactions(walletManager, asyncStorage)
notifications.forEach((notification) => transactionReceivedSubject.next(notification))
})

return () => {
Expand Down
32 changes: 16 additions & 16 deletions apps/wallet-mobile/translations/messages/src/AppNavigator.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,59 +4,59 @@
"defaultMessage": "!!!Enter PIN",
"file": "src/AppNavigator.tsx",
"start": {
"line": 230,
"line": 235,
"column": 17,
"index": 8390
"index": 8675
},
"end": {
"line": 233,
"line": 238,
"column": 3,
"index": 8480
"index": 8765
}
},
{
"id": "components.initialization.custompinscreen.title",
"defaultMessage": "!!!Set PIN",
"file": "src/AppNavigator.tsx",
"start": {
"line": 234,
"line": 239,
"column": 18,
"index": 8500
"index": 8785
},
"end": {
"line": 237,
"line": 242,
"column": 3,
"index": 8598
"index": 8883
}
},
{
"id": "global.actions.dialogs.walletKeysInvalidated.title",
"defaultMessage": "!!!Auth with OS changes",
"file": "src/AppNavigator.tsx",
"start": {
"line": 238,
"line": 243,
"column": 25,
"index": 8625
"index": 8910
},
"end": {
"line": 241,
"line": 246,
"column": 3,
"index": 8739
"index": 9024
}
},
{
"id": "global.actions.dialogs.biometricsChange.message",
"defaultMessage": "!!!Auth with OS changed detected",
"file": "src/AppNavigator.tsx",
"start": {
"line": 242,
"line": 247,
"column": 27,
"index": 8768
"index": 9053
},
"end": {
"line": 245,
"line": 250,
"column": 3,
"index": 8889
"index": 9174
}
}
]
Loading

0 comments on commit 5ca0641

Please sign in to comment.