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

Local notifications #21

Merged
merged 6 commits into from
Jan 30, 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
6 changes: 5 additions & 1 deletion app.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@
}
},
"owner": "kir-dev",
"plugins": ["expo-router"]
"plugins": ["expo-router"],
"notification": {
"icon": "./assets/notification-icon.png",
"color": "#000000"
}
}
}
2 changes: 2 additions & 0 deletions app/(tabs)/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { TabbarBackground } from '../../components/tabbar/tabbar-background';
import { TabbarIcon } from '../../components/tabbar/tabbar-icon';
import { TabbarLabel } from '../../components/tabbar/tabbar-label';
import { useNotificationObserver } from '../../hooks/use-notification-observer';
import { colors } from '../../theme/colors';

export default function TabsLayout() {
useNotificationObserver();
const { top, bottom, left, right } = useSafeAreaInsets();
return (
<Tabs
Expand Down
Binary file added assets/notification-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 6 additions & 5 deletions components/schedule/favorite-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,22 @@ import { useMemo } from 'react';
import { Pressable } from 'react-native';

import { useFavoriteEvents } from '../../contexts/favorite-events.context';
import { ScheduleEvent } from '../../types/schedule-event.type';

interface FavoriteButtonProps {
eventId: string;
event: ScheduleEvent;
}

export function FavoriteButton({ eventId }: FavoriteButtonProps) {
export function FavoriteButton({ event }: FavoriteButtonProps) {
const { isFavoriteEvent, addFavoriteEvent, removeFavoriteEvent } = useFavoriteEvents();

const isFavorite = useMemo(() => isFavoriteEvent(eventId), [eventId, isFavoriteEvent]);
const isFavorite = useMemo(() => isFavoriteEvent(event.id), [event, isFavoriteEvent]);

const onPress = () => {
if (isFavorite) {
removeFavoriteEvent(eventId);
removeFavoriteEvent(event.id);
} else {
addFavoriteEvent(eventId);
addFavoriteEvent(event);
}
};

Expand Down
2 changes: 1 addition & 1 deletion components/schedule/schedule-details-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function ScheduleDetailsPage({ id }: ScheduleDetailsPageProps) {
</Subtitle>
</Header>
<StyledText className='mx-5 text-xl'>{data?.description}</StyledText>
<FavoriteButton eventId={id} />
<FavoriteButton event={data} />
</Screen>
);
}
14 changes: 10 additions & 4 deletions contexts/favorite-events.context.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react';

import { FavoriteEventStorageService } from '../services/favorite-event.service';
import { NotificationService } from '../services/notification.service';
import { FavoriteEvent } from '../types/favorite-event.type';
import { ScheduleEvent } from '../types/schedule-event.type';

type FavoriteEventsContextType =
| {
favoriteEvents: FavoriteEvent[];
addFavoriteEvent: (eventId: string) => void;
addFavoriteEvent: (event: ScheduleEvent) => void;
removeFavoriteEvent: (eventId: string) => void;
isFavoriteEvent: (eventId: string) => boolean;
}
Expand All @@ -17,14 +19,18 @@ const FavoriteEventsContext = createContext<FavoriteEventsContextType>(undefined
export function FavoriteEventsProvider({ children }: PropsWithChildren) {
const [favoriteEvents, setFavoriteEvents] = useState<FavoriteEvent[]>([]);

function addFavoriteEvent(eventId: string) {
setFavoriteEvents((prev) => [...prev, { eventId }]);
FavoriteEventStorageService.addFavoriteEvent(eventId);
async function addFavoriteEvent(event: ScheduleEvent) {
const notificationId = await NotificationService.scheduleEventNotification(event);
const favoriteEvent = { eventId: event.id, notificationId };
setFavoriteEvents((prev) => [...prev, favoriteEvent]);
FavoriteEventStorageService.addFavoriteEvent(favoriteEvent);
}

function removeFavoriteEvent(eventId: string) {
const favoriteEvent = favoriteEvents.find((item) => item.eventId === eventId);
setFavoriteEvents((prev) => prev.filter((item) => item.eventId !== eventId));
FavoriteEventStorageService.removeFavoriteEvent(eventId);
NotificationService.removeScheduledNotification(favoriteEvent?.notificationId);
}

function isFavoriteEvent(eventId: string) {
Expand Down
35 changes: 35 additions & 0 deletions hooks/use-notification-observer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as Notifications from 'expo-notifications';
import { useRouter } from 'expo-router';
import { useEffect } from 'react';

//From: https://docs.expo.dev/versions/latest/sdk/notifications/#handle-push-notifications-with-navigation
export function useNotificationObserver() {
const router = useRouter();
useEffect(() => {
let isMounted = true;

function redirect(notification: Notifications.Notification) {
const tab = notification.request.content.data?.tab;
const screen = notification.request.content.data?.screen;
const id = notification.request.content.data?.id;
if (tab) router.push({ pathname: tab });
if (screen) router.push({ pathname: `${tab}/${screen}`, params: { id } });
}

Notifications.getLastNotificationResponseAsync().then((response) => {
if (!isMounted || !response?.notification) {
return;
}
redirect(response?.notification);
});

const subscription = Notifications.addNotificationResponseReceivedListener((response) => {
redirect(response.notification);
});

return () => {
isMounted = false;
subscription.remove();
};
}, []);
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
"date-fns": "^3.2.0",
"expo": "~49.0.21",
"expo-constants": "~14.4.2",
"expo-device": "~5.4.0",
"expo-linking": "~5.0.2",
"expo-router": "^2.0.0",
"expo-notifications": "~0.20.1",
"expo-router": "^2.0.14",
"expo-splash-screen": "~0.20.5",
"expo-status-bar": "~1.6.0",
"nativewind": "^2.0.11",
Expand Down
4 changes: 2 additions & 2 deletions services/favorite-event.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ export class FavoriteEventStorageService {
}
}

static async addFavoriteEvent(eventId: string): Promise<void> {
static async addFavoriteEvent(favorite: FavoriteEvent): Promise<void> {
try {
const favoriteEvents = await this.listFavoriteEvents();
const newFavoriteEvents = [...favoriteEvents, { eventId }];
const newFavoriteEvents = [...favoriteEvents, favorite];
await this.saveFavoriteEvents(newFavoriteEvents);
} catch (error) {
console.log(error);
Expand Down
53 changes: 53 additions & 0 deletions services/notification.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { isBefore } from 'date-fns';
import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';

import { ScheduleEvent } from '../types/schedule-event.type';

export class NotificationService {
static notificationEnabled = false;

private static async registerForPushNotifications() {
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.HIGH,
});
}

const { status: existingStatus } = await Notifications.getPermissionsAsync();
this.notificationEnabled = existingStatus === 'granted';
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
this.notificationEnabled = status === 'granted';
}
}

static async scheduleEventNotification(event: ScheduleEvent) {
await this.registerForPushNotifications();
if (!this.notificationEnabled) {
console.log('Notification permission not granted, not scheduling notification');
return;
}
if (isBefore(new Date(event.start), new Date())) {
console.log('Event is in the past, not scheduling notification');
return;
}

const triggerDate = new Date(event.start);

return await Notifications.scheduleNotificationAsync({
content: {
title: event.title,
body: `Hamarosan kezdődik a(z) ${event.location} teremben!`,
data: { tab: 'schedule', screen: 'schedule-details', id: event.id },
},
trigger: triggerDate,
});
}

static async removeScheduledNotification(notificationId: string | undefined): Promise<void> {
if (!notificationId) return;
await Notifications.cancelScheduledNotificationAsync(notificationId);
}
}
1 change: 1 addition & 0 deletions types/favorite-event.type.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export type FavoriteEvent = {
eventId: string;
notificationId: string | undefined;
};
Loading
Loading