Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374import {useCallback, useEffect} from 'react'import {Platform} from 'react-native'import * as Application from 'expo-application'import * as Notifications from 'expo-notifications'import {getBadgeCountAsync, setBadgeCountAsync} from 'expo-notifications'import {type Client} from '@atproto/lex'import BackgroundNotificationHandler from '@bsky.app/expo-background-notification-handler'import debounce from 'lodash.debounce'
import { NOTIF_SERVICE, PUBLIC_APPVIEW_DID, PUBLIC_STAGING_APPVIEW_DID,} from '#/lib/constants'import {logger as notyLogger} from '#/lib/notifications/util'import {isNetworkError} from '#/lib/strings/errors'import {type SessionAccount, usePdsClient, useSession} from '#/state/session'import {useAnalytics} from '#/analytics'import {IS_DEV, IS_NATIVE} from '#/env'import {app} from '#/lexicons'
/** * A resumed single-use account client paired with the account's service origin * and handle. Produced by `createTemporaryClientsAndResume` (session util) and * consumed by {@link unregisterPushToken}, which needs the service host to pick * the appview DID and the handle for a debug log line without reaching into the * session internals. */export type TemporaryPushClient = { client: Client service: string handle: string}
/** * @private * Registers the device's push notification token with the Bluesky server. */async function _registerPushToken({ client, currentAccount, token, extra = {},}: { client: Client currentAccount: SessionAccount token: Notifications.DevicePushToken extra?: { ageRestricted?: boolean }}) { try { const payload: app.bsky.notification.registerPush.$InputBody = { serviceDid: currentAccount.service?.includes('staging') ? PUBLIC_STAGING_APPVIEW_DID : PUBLIC_APPVIEW_DID, platform: Platform.OS, token: token.data, appId: Application.applicationId ?? 'community.blacksky.app', ageRestricted: extra.ageRestricted ?? false, }
notyLogger.debug(`registerPushToken: registering`, {...payload})
await client.call(app.bsky.notification.registerPush, payload, { service: NOTIF_SERVICE, })
notyLogger.debug(`registerPushToken: success`) } catch (error) { if (!isNetworkError(error)) { notyLogger.warn(`registerPushToken: failed`, {safeMessage: error}) } }}
/** * @private * Debounced version of `_registerPushToken` to prevent multiple calls. */const _registerPushTokenDebounced = debounce(_registerPushToken, 100)
/** * Hook to register the device's push notification token with the Bluesky. If * the user is not logged in, this will do nothing. * * Use this instead of using `_registerPushToken` or * `_registerPushTokenDebounced` directly. */export function useRegisterPushToken() { const client = usePdsClient() const {currentAccount} = useSession()
return useCallback( ({ token, isAgeRestricted, }: { token: Notifications.DevicePushToken isAgeRestricted: boolean }) => { if (!currentAccount) return return _registerPushTokenDebounced({ client, currentAccount, token, extra: { ageRestricted: isAgeRestricted, }, }) }, [client, currentAccount], )}
/** * Retreive the device's push notification token, if permissions are granted. */async function getPushToken() { const granted = (await Notifications.getPermissionsAsync()).granted notyLogger.debug(`getPushToken`, {granted}) if (granted) { try { return await Notifications.getDevicePushTokenAsync() } catch (error) { notyLogger.debug(`getPushToken: failed`, {safeMessage: error}) } }}
/** * Hook to get the device push token and register it with the Bluesky server. * Should only be called after a user has logged-in, since registration is an * authed endpoint. * * N.B. A previous regression in `expo-notifications` caused * `addPushTokenListener` to not fire on Android after calling * `getPushToken()`. Therefore, as insurance, we also call * `registerPushToken` here. * * Because `registerPushToken` is debounced, even if the the listener _does_ * fire, it's OK to also call `registerPushToken` below since only a single * call will be made to the server (ideally). This does race the listener (if * it fires), so there's a possibility that multiple calls will be made, but * that is acceptable. * * @see https://github.com/expo/expo/issues/28656 * @see https://github.com/expo/expo/issues/29909 * @see https://github.com/bluesky-social/social-app/pull/4467 */export function useGetAndRegisterPushToken() { const registerPushToken = useRegisterPushToken() return useCallback( async ({ isAgeRestricted: isAgeRestrictedOverride, }: { isAgeRestricted?: boolean } = {}) => { if (!IS_NATIVE || IS_DEV) return
/** * This will also fire the listener added via `addPushTokenListener`. That * listener also handles registration. */ const token = await getPushToken()
notyLogger.debug(`useGetAndRegisterPushToken`, { token: token ?? 'undefined', })
if (token) { /** * The listener should have registered the token already, but just in * case, call the debounced function again. */ registerPushToken({ token, isAgeRestricted: isAgeRestrictedOverride ?? false, }) }
return token }, [registerPushToken], )}
/** * Hook to register the device's push notification token with the Bluesky * server, as well as listen for push token updates, should they occurr. * * Registered via the shell, which wraps the navigation stack, meaning if we * have a current account, this handling will be registered and ready to go. */export function useNotificationsRegistration() { const {currentAccount} = useSession() const registerPushToken = useRegisterPushToken() const getAndRegisterPushToken = useGetAndRegisterPushToken()
useEffect(() => { /** * We want this to init right away _after_ we have a logged in user, and * _after_ we've loaded their age assurance state. */ if (!currentAccount) return
notyLogger.debug(`useNotificationsRegistration`)
/** * Init push token, if permissions are granted already. If they weren't, * they'll be requested by the `useRequestNotificationsPermission` hook * below. */ getAndRegisterPushToken()
/** * Register the push token with the Bluesky server, whenever it changes. * This is also fired any time `getDevicePushTokenAsync` is called. * * Since this is registered immediately after `getAndRegisterPushToken`, it * should also detect that getter and be fired almost immediately after this. * * According to the Expo docs, there is a chance that the token will change * while the app is open in some rare cases. This will fire * `registerPushToken` whenever that happens. * * @see https://docs.expo.dev/versions/latest/sdk/notifications/#addpushtokenlistenerlistener */ const subscription = Notifications.addPushTokenListener(async token => { registerPushToken({ token, isAgeRestricted: false, }) notyLogger.debug(`addPushTokenListener callback`, {token}) })
return () => { subscription.remove() } }, [currentAccount, getAndRegisterPushToken, registerPushToken])}
/** * Tracks whether we have already shown the OS notification permission prompt * during this app session. On Android `canAskAgain` stays true after a single * in-app denial, so without this guard a later call site (e.g. Home after * Login) would surface a second prompt. Resets on app restart. */let hasRequestedPermissionsThisSession = false
export function useRequestNotificationsPermission() { const ax = useAnalytics() const {currentAccount} = useSession() const getAndRegisterPushToken = useGetAndRegisterPushToken()
return async ( context: 'StartOnboarding' | 'AfterOnboarding' | 'Login' | 'Home', ) => { const permissions = await Notifications.getPermissionsAsync()
if ( !IS_NATIVE || permissions?.status === 'granted' || (permissions?.status === 'denied' && !permissions.canAskAgain) ) { return } if (context === 'AfterOnboarding') { return } if (context === 'Home' && !currentAccount) { return }
if (hasRequestedPermissionsThisSession) { return } hasRequestedPermissionsThisSession = true
const res = await Notifications.requestPermissionsAsync({ ios: { /* * These three default to true when no argument is passed to * `requestPermissionsAsync`, but passing an options object opts out of * that default, so we have to set them explicitly to preserve the * existing behavior. */ allowAlert: true, allowBadge: true, allowSound: true, /* * Adds an in-app notification settings button to the system Settings * screen for Bluesky. When tapped, iOS calls back into the app, which * we route to the in-app notification settings (see the * NotificationSettings module in expo-bluesky-swiss-army). */ provideAppNotificationSettings: true, }, })
ax.metric(`notifications:request`, { context: context, status: res.status, })
if (res.granted) { if (currentAccount) { /** * If we have an account in scope, we can safely call * `getAndRegisterPushToken`. */ getAndRegisterPushToken() } else { /** * Right after login, `currentAccount` in this scope will be undefined, * but calling `getPushToken` will result in `addPushTokenListener` * listeners being called, which will handle the registration with the * Bluesky server. */ getPushToken() } } }}
export async function decrementBadgeCount(by: number) { if (!IS_NATIVE) return
let count = await getBadgeCountAsync() count -= by if (count < 0) { count = 0 }
await BackgroundNotificationHandler.setBadgeCountAsync(count) await setBadgeCountAsync(count)}
export async function resetBadgeCount() { await BackgroundNotificationHandler.setBadgeCountAsync(0) await setBadgeCountAsync(0)}
export async function unregisterPushToken(clients: TemporaryPushClient[]) { if (!IS_NATIVE) return
try { const token = await getPushToken() if (token) { for (const {client, service, handle} of clients) { await client.call( app.bsky.notification.unregisterPush, { serviceDid: service.includes('staging') ? PUBLIC_STAGING_APPVIEW_DID : PUBLIC_APPVIEW_DID, platform: Platform.OS, token: token.data, appId: Application.applicationId ?? 'community.blacksky.app', }, { service: NOTIF_SERVICE, }, ) notyLogger.debug(`Push token unregistered for ${handle}`) } } else { notyLogger.debug('Tried to unregister push token, but could not find one') } } catch (error) { notyLogger.debug('Failed to unregister push token', {message: error}) }}