Skip to content
This repository was archived by the owner on Sep 4, 2024. It is now read-only.

Push notif v2 #41

Open
wants to merge 60 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
99f7070
gitignore for Jetbiran IDE
jimlo7760 Feb 27, 2024
51e3e92
test
hengruiren Feb 27, 2024
fdfb8f4
constructor
hengruiren Mar 3, 2024
601e195
ios apn
hengruiren Mar 9, 2024
d01a12c
Android FCM
hengruiren Mar 9, 2024
27ec3b9
merge
hengruiren Mar 9, 2024
557a7fc
Add package name and version code to the android app.
jimlo7760 Mar 12, 2024
9a2f1cc
Link the local project to Firebase
jimlo7760 Mar 12, 2024
45e2db5
add fire base messaging framework
jimlo7760 Mar 12, 2024
1312e81
error message and fix
hengruiren Mar 13, 2024
6cfb81e
Allow clients to specify more notification parameters, such as title …
hengruiren Mar 13, 2024
acfd4bb
add date and time
hengruiren Mar 13, 2024
36657d0
add EAS build
jimlo7760 Mar 13, 2024
b8448d6
match the version of expo
jimlo7760 Mar 13, 2024
8657b39
add a test page for testing push notification
jimlo7760 Mar 13, 2024
536204f
add necessary modules for expo notification
jimlo7760 Mar 13, 2024
c0aa12a
express structure and initialize APN
hengruiren Mar 15, 2024
534c38f
Merge branch 'push_notif_V2' of https://github.com/hack-rpi/HackRPI-M…
hengruiren Mar 15, 2024
673f0de
apn little change
hengruiren Mar 15, 2024
48e4d4c
FCM little change
hengruiren Mar 15, 2024
8f44577
feedback function
hengruiren Mar 29, 2024
c73d728
add partially set up instruction
jimlo7760 Mar 31, 2024
1d57660
Merge branch 'push_notif_V2' of https://github.com/hack-rpi/HackRPI-M…
jimlo7760 Mar 31, 2024
73f6435
Update node.js
hengruiren Apr 2, 2024
de1a669
Merge branch 'push_notif_V2' of https://github.com/hack-rpi/HackRPI-M…
hengruiren Apr 2, 2024
a9f81d8
update user2
hengruiren Apr 2, 2024
e5c64b6
Update node.js
hengruiren Apr 2, 2024
29d2690
complete the set up page
jimlo7760 Apr 2, 2024
790aa49
fix bug for apn and fcm
hengruiren Apr 4, 2024
4018ad4
overview doc
hengruiren Apr 4, 2024
b867817
Update Notifications_Overview.md
hengruiren Apr 5, 2024
a5b5c79
quickGuide
hengruiren Apr 5, 2024
6959667
Update quick guide
hengruiren Apr 5, 2024
1df7dfe
update quickguide
hengruiren Apr 5, 2024
b2bbbf2
add more comments on the setup.md
jimlo7760 Apr 6, 2024
8d3c719
clarify the instruction
jimlo7760 Apr 6, 2024
8d57ea8
Complete the set up wiki page
jimlo7760 Apr 7, 2024
2fa3716
Add necessary packages to implement push notification
jimlo7760 Apr 7, 2024
f0cfa43
Functions to implement notification pushing
jimlo7760 Apr 8, 2024
bb28a00
Implement push notification function. Add some console log to debug t…
jimlo7760 Apr 9, 2024
ee28bd7
[Test] Schedule the push notification 10s after the user is clicked
jimlo7760 Apr 12, 2024
8916b6d
Schedule the push notification five minute before a given time
jimlo7760 Apr 12, 2024
9b49126
Add parameters to push notification corresponds to the workshop.
jimlo7760 Apr 12, 2024
16c1dac
Add comments for testings. Ready for PR!
jimlo7760 Apr 13, 2024
a2456b1
Delete the redundant testing page
jimlo7760 Apr 14, 2024
12d2403
Set the push notification is on when the page is loaded
jimlo7760 Apr 14, 2024
51d6278
Notification of the workshops is now scheduled by default (i.e. when …
jimlo7760 Apr 14, 2024
3225e7a
Complete the notification cancellation when the "bell-off" icon is ac…
jimlo7760 Apr 15, 2024
50e0395
Update Notifications_Overview.md
hengruiren Apr 17, 2024
41beb85
setup update
hengruiren Apr 17, 2024
6421282
Update setup.md
hengruiren Apr 17, 2024
44dcf3d
Optimize the set up instruction
jimlo7760 Apr 17, 2024
24f685a
little change
hengruiren Apr 17, 2024
a631224
Merge branch 'push_notif_V2' of https://github.com/hack-rpi/HackRPI-M…
jimlo7760 Apr 17, 2024
274e22e
Merge branch 'push_notif_V2' of https://github.com/hack-rpi/HackRPI-M…
jimlo7760 Apr 17, 2024
f069c85
Add comments and separate every process of push notification into blo…
jimlo7760 Apr 17, 2024
d3a96d0
Update quickGuide.md
hengruiren Apr 17, 2024
0f5ffd1
Update quickGuide.md
hengruiren Apr 17, 2024
52effd1
Add test instruction to the setup.md
jimlo7760 Apr 17, 2024
6f45323
Fix the typo
jimlo7760 Apr 18, 2024
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
Binary file modified .DS_Store
Binary file not shown.
5 changes: 5 additions & 0 deletions HackRPIEventApp2023/.idea/.gitignore

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

6 changes: 6 additions & 0 deletions HackRPIEventApp2023/.idea/vcs.xml

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

1 change: 1 addition & 0 deletions HackRPIEventApp2023/Box/Calander.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const Calander = () => {
Location={event.WorkShop_Location}
Description={event.WorkShop_Description}
isRed={Active}
dateAndTime={event.WorkShop_Date + " " + event.WorkShop_StartTime}
/>
);
})}
Expand Down
150 changes: 148 additions & 2 deletions HackRPIEventApp2023/Box/CalanderObject.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,168 @@ import React, { useState } from "react";
import { View, StyleSheet } from "react-native";
import { Feather } from "@expo/vector-icons";
import EventObject from "./EventObject"; // Import the EventObject component
import { useEffect, useRef} from 'react';
import { Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';

Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
}),
});

async function sendPushNotification(expoPushToken) {
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),
});
}

async function registerForPushNotificationsAsync() {
let token;

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

if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
token = await Notifications.getExpoPushTokenAsync({
projectId: Constants.expoConfig.extra.eas.projectId,
});
console.log(token);
} else {
alert('Must use physical device for Push Notifications');
}

return token.data;
}


//reusable component that ties an event object to it's notification bell
const CalanderObject = ({
workshop_Title,
Time,
Location,
Presenter,
Description,
isRed,
dateAndTime,
}) => {
const [isActive, setIsActive] = useState(false); // Define isActive state
const [expoPushToken, setExpoPushToken] = useState('');
const notificationListener = useRef();
const responseListener = useRef();

const [notificationId, setNotificationId] = useState(null); // record the scheduled notification id

const handleClick = () => {
// Function to toggle the isActive state
const handleClick =async() => {
setIsActive(!isActive);

};

useEffect(() => {
registerForPushNotificationsAsync().then(token => setExpoPushToken(token));

notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
console.log(notification);
});

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

// parsing the dateAndTime String
const notiTime = dateAndTime;
const [dateString, timeString] = notiTime.split(' ');
const [year, month, day] = dateString.split('-');
const [hours, minutes] = timeString.split(':');

const eventTime = new Date(year, month - 1, day, hours, minutes); // create a Date object for event
const triggerTime = new Date(eventTime.getTime() - 5 * 60 * 1000); // subtract 5 minutes from event time

const currentTime = new Date(); // get current time


const notiPush = !isActive; // notiPush represents the status of notification need to push or not.
if (notiPush) {
const scheduleNotification = async () => {
try {
console.log('Current Time: ', currentTime, 'Trigger Time: ', triggerTime);
const delay = triggerTime.getTime() - currentTime.getTime(); // calculate delay in milliseconds
console.log('Workshop Title: ', workshop_Title, 'Date and Time: ', dateAndTime, 'Delay: ', delay);


if (delay > 0) { // when the workshop is in the future
const notificationId = await Notifications.scheduleNotificationAsync({
content: {
title: 'Workshop Reminder', // notification title can be changed here!
body: 'Your workshop' + workshop_Title + 'is starting in 5 minutes', // notification body can be changed here!
},
trigger: {
seconds: Math.floor(delay / 1000), // The difference between the event time and the current time in seconds
},
});
setNotificationId(notificationId);
console.log(`Notification scheduled with ID: ${notificationId}`);
} else {
console.log(isActive); // console log the error when not in the future, because the passed workshop will not display in the page.
console.log('The workshop has passed. Notification not scheduled.');
}
} catch (error){ // one possibility to cause this error would be the push notification environment is not properly set up.
console.error('Failed to schedule notification:', error);
// Handle the error, e.g., show an error message to the user
alert('Failed to schedule notification. Please try again.');
}
};

scheduleNotification();
}else{ // if the "bell-off" icon is active, cancel the scheduled notification
if (notificationId) {
console.log('Cancelling notification with ID: ', notificationId);
Notifications.cancelScheduledNotificationAsync(notificationId);
setNotificationId(null);
console.log('Notification cancelled');
}
}

return () => {
Notifications.removeNotificationSubscription(notificationListener.current);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, [isActive, dateAndTime, workshop_Title]);

return (
<View style={styles.container}>
<EventObject
Expand Down
4 changes: 2 additions & 2 deletions HackRPIEventApp2023/Box/WorkShops.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
{
"WorkShop_Title": "Participant Check-In",
"WorkShop_Presenter": "TBD",
"WorkShop_Date": "2024-11-28",
"WorkShop_StartTime": "10:00",
"WorkShop_Date": "2024-4-17",
"WorkShop_StartTime": "00:39",
"WorkShop_EndTime": "18:00",
"WorkShop_Location": "DCC Lobby",
"WorkShop_Description": "TBD"
Expand Down
139 changes: 139 additions & 0 deletions HackRPIEventApp2023/Components/Notification/Notifications_Overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# Notifications Overview

Notifications are an essential aspect of mobile and web applications, offering a way to convey important information to users, whether the app is running on the device or not. For instance, sports apps can notify users of their favorite team's scores. Notifications can also prompt apps to download data and update their interfaces, displaying alerts, playing sounds, or marking the app's icon.

## Display

Notifications appear on iOS devices' lock and home screens. They can be generated locally within an app or remotely from a managed server. Local notifications are set based on specific conditions like time or location. Remote notifications are generated by a server and sent through the Apple Push Notification Service (APNs), which handles their delivery.

## Framework Capabilities

The framework for managing notifications allows applications to:

- Define supported notification types.
- Schedule local notifications.
- Handle and respond to incoming notifications.
- Define custom actions associated with notification types.

Although the system strives to deliver notifications promptly, immediate delivery cannot be guaranteed. The PushKit framework provides a more timely delivery mechanism for specific notification types, such as VoIP or watchOS features.

For web applications, especially on Safari version 16.0 and higher, remote notifications can be generated using Push API code, working across Safari and other browsers, managed by a server.

## Integration with Siri

Siri can use the information from your app's notifications to make suggestions to users in Search, News, Safari, and other apps. Users can manage this feature through Siri and search settings.

## Design Guidelines

For notification design, it's recommended to follow the Human Interface Guidelines to ensure they are user-friendly and effective.

## Topics

### Notification Management

- Central objects and delegates like `UNUserNotificationCenter` manage notification-related activities and responses.

### Remote Notifications

- Setting up a remote notification server and registering your app with APNs to send notifications.

### Notification Requests

- Creating delivery requests for local notifications and accessing delivered notification content.

### Safari Push Notifications

- Sending web push notifications for web apps and browsers, including Safari.

### Notification Content

- Modifying and inspecting notification payloads.

### Triggers

- Setting conditions for notification delivery, including time, location, and remote triggers.

### Notification Categories and User Actions

- Defining custom actions and categories for notifications to enhance user interactions.

This summary covers the extensive capabilities and considerations for implementing notifications in applications, addressing both local and remote notifications, user interactions, and integration with system services like Siri and APNs.

## Importance of Timing and Relevance

- **User Preferences and Customization:** Allowing users to customize notification preferences, including types and frequency, enhances user experience and satisfaction.
- **Smart Timing:** Leveraging user behavior data to schedule notifications for optimal engagement times can significantly increase interaction rates.

## Advanced Notification Features

### Interactive Notifications

Interactive notifications go beyond basic alerts by enabling users to take action directly from the notification interface. This could include replying to a message, marking a task as complete, or even controlling playback for media apps.

### Rich Media Notifications

Integrating images, GIFs, video, and audio content within notifications can make them more engaging and informative. Rich media notifications are especially useful for news apps, e-commerce, and social platforms where visual content can convey a message more effectively than text alone.

### Analytics and Optimization

Implementing analytics to track how users interact with notifications is crucial for understanding their effectiveness. Metrics such as open rates, interaction times, and conversion rates can inform strategies for optimizing notification content, frequency, and timing.

## Challenges and Considerations

While notifications are powerful tools for engagement, developers must navigate challenges related to user privacy, device limitations, and platform-specific regulations. Obtaining user consent and providing clear options for managing notification preferences are essential for maintaining trust and compliance with privacy laws.

### Battery Life and Performance Impacts

Frequent notifications can impact device performance and battery life, especially if they trigger background activities. Balancing the need for timely updates with device resource constraints is crucial for ensuring a positive user experience.

### Platform-Specific Features and Limitations

Developers must consider the unique capabilities and limitations of each platform (iOS, Android, Web) when designing notification strategies. This includes platform-specific design guidelines, notification formats, and delivery mechanisms.

## Security and Privacy Enhancements

With growing concerns over data privacy and security, notifications must be designed with privacy in mind.

- **End-to-End Encryption:** For sensitive information, notifications should employ end-to-end encryption to ensure that content is only accessible to the intended recipient.
- **Minimal Data Use:** Design notifications to convey essential information without over-reliance on personal data, adhering to the principle of data minimization.

## Cross-Platform Notification Strategies

- **Unified Experience Across Devices:** Ensuring a seamless notification experience across mobile, web, and wearable devices is key to maintaining user engagement in a multi-device world.
- **Platform-Specific Optimization:** While aiming for consistency, tailor notification strategies to exploit the unique features and adhere to the guidelines of each platform.

Data-Driven Notification Design

Analyzing User Engagement
Behavioral Analytics:
Tools and techniques for monitoring how users interact with notifications to fine-tune timing and content.
A/B Testing: Implementing controlled experiments to compare different notification strategies and identify the most effective ones.
User Segmentation
Demographic Segmentation:
Tailoring notifications based on user demographics to increase relevance and engagement.
Behavioral Segmentation: Delivering personalized notifications based on past user actions and preferences.
Enhancing User Experience

Notification Priority and Management
Priority Settings:
Allowing users to set notification priorities to manage the urgency and visibility of alerts.
Silent Notifications: Notifications that deliver information silently, without alerting the user immediately.
Customizable Interfaces

User-Controlled Settings:
Providing extensive options for users to customize the look and feel of notifications.
Theme Integration:
Ensuring that notifications adhere to the app's theme and user-selected modes, such as dark mode.
Technical Aspects

Backend Infrastructure

Scalability Challenges:
Building a backend capable of handling a large number of notifications simultaneously.
Reliability Measures: Techniques to ensure that notifications are delivered reliably, even in high-load scenarios.
API Integration and Development

Standard APIs and Protocols:
Utilizing standard APIs for notification delivery, such as Google's Firebase Cloud Messaging (FCM) and Apple's APNs.
Custom API Development: Developing bespoke APIs for specific application needs and complex notification logic.
Compliance and Legal Considerations
Loading