Compare commits

...

2 Commits

Author SHA1 Message Date
ed7c6d630c Fixed notifications not being saved unless you clicked on them
- Added automatic cleanup of old notifications after 60 days
- Added deduplicateItems function to prevent the same notification to appear multiple times
- Fixed timestamp
2025-10-18 19:40:16 +02:00
26e5b0ae6f Completely reworked the app by starting fresh
- Now you can just swipe to access categories
- Redone side menu
- Inital API input screen is more legible
- A goose as an icon
- Proper display and internal name
- Correct handling of incoming data
2025-10-16 16:41:01 +02:00
30 changed files with 6335 additions and 1868 deletions

2
.gitignore vendored
View File

@ -44,3 +44,5 @@ app-example
google-services.json google-services.json
build-*
*.apk

131
README.md
View File

@ -1,50 +1,119 @@
# Welcome to your Expo app 👋 # Notifier app
This is an [Expo](https://expo.dev) project created with [`create-expo-app`](https://www.npmjs.com/package/create-expo-app). A React Native mobile application for receiving push notifications.
## Get started ## Features
1. Install dependencies - **Secure API Authentication** - API key-based authentication to connect to the `backend-api`
- **Notification Storage** - Notifications are saved locally and deleted after 60 days
- **Category Organization** - Notifications are organized into categories and a complete history is displayed in Home
- **Drawer Navigation** - Easy navigation between different notification categories
- **Interactive Links** - Tap on notification links to open them in your device's browser
- **Logout Functionality** - Securely unregister your device and clear all local data
```bash <p align="center">
npm install <img src="assets/images/main_menu.jpg" alt="Main Menu" width="30%"/>
``` <img src="assets/images/sidemenu.jpg" alt="Side Menu" width="30%"/>
<img src="assets/images/rr_category.jpg" alt="RR Category" width="30%"/>
</p>
2. Start the app ## Prerequisites
```bash - Node.js (v14 or higher)
npx expo start - Firebase account with google-services.json
``` - Expo account with Firebase Admin SDK private key imported
- Installed eas-cli
- Android SDK 36
- Physical Android device (push notifications don't work on simulators/emulators)
- API key
In the output, you'll find options to open the app in a
- [development build](https://docs.expo.dev/develop/development-builds/introduction/)
- [Android emulator](https://docs.expo.dev/workflow/android-studio-emulator/)
- [iOS simulator](https://docs.expo.dev/workflow/ios-simulator/)
- [Expo Go](https://expo.dev/go), a limited sandbox for trying out app development with Expo
You can start developing by editing the files inside the **app** directory. This project uses [file-based routing](https://docs.expo.dev/router/introduction). ## Building from scratch
## Get a fresh project
When you're ready, run:
1. Clone the repository:
```bash ```bash
npm run reset-project git clone <repository-url>
cd <project-directory>
``` ```
This command will move the starter code to the **app-example** directory and create a blank **app** directory where you can start developing. 2. Install dependencies:
```bash
npm install
```
## Learn more 3. Copy google-services.json to root directory and delete .gitignore file (or comment out google-services.json)
To learn more about developing your project with Expo, look at the following resources: 4. Use EAS to build and follow along
```bash
eas build --profile release --local --platform android
```
- [Expo documentation](https://docs.expo.dev/): Learn fundamentals, or go into advanced topics with our [guides](https://docs.expo.dev/guides). ## Configuration
- [Learn Expo tutorial](https://docs.expo.dev/tutorial/introduction/): Follow a step-by-step tutorial where you'll create a project that runs on Android, iOS, and the web.
## Join the community ### Backend URL
Join our community of developers creating universal apps. The app connects to the notification backend at:
```
https://notifier.gansejunge.com
```
- [Expo on GitHub](https://github.com/expo/expo): View our open source platform and contribute. To change this, modify the `API_URL` constant in `index.tsx`.
- [Discord community](https://chat.expo.dev): Chat with Expo users and ask questions.
### Categories
Categories are defined in `types/Category.ts`. Special categories:
- **Home** - View all notifications
- **Utility** - Default category for uncategorized notifications
## Technical Details
### Notification Data Structure
Notifications should include the following data fields from your backend:
```json
{
"title": "Notification Title",
"body": "Notification message text",
"data": {
"category": "utility",
"link": "https://example.com",
"timestamp": 1760734800
}
}
```
- `category` - Optional. Defaults to "utility" if not provided
- `link` - Optional. Set to "#" if no link should be shown
- `timestamp` - Optional. Defaults to when the notification was received when empty
## Project Structure
```
├── index.tsx # Main app component
├── hooks/
│ ├── usePushNotifications.ts # Push notification registration
│ └── useNotificationListener.ts # Notification receiving and storage
├── types/
│ ├── Category.ts # Category definitions
│ └── Item.ts # Notification item type
└── styles/
└── styles.ts # App styling
```
## API Endpoints
The app communicates with these backend endpoints:
- **POST /register-token** - Register device for push notifications
- Headers: `X-API-Key: <your-api-key>`
- Body: `{ token, platform, app_ver, locale, topics }`
- **POST /unregister-token** - Unregister device
- Headers: `X-API-Key: <your-api-key>`
- Body: `{ token, platform, app_ver, locale, topics }`

View File

@ -1,44 +1,30 @@
{ {
"expo": { "expo": {
"name": "my-drawer-app", "name": "Notifier",
"slug": "my-drawer-app", "slug": "notifier",
"version": "1.0.0", "version": "1.0.0",
"orientation": "portrait", "orientation": "portrait",
"icon": "./assets/images/icon.png", "icon": "./assets/images/icon.png",
"scheme": "mydrawerapp", "scheme": "notifier",
"userInterfaceStyle": "automatic", "userInterfaceStyle": "automatic",
"newArchEnabled": true, "newArchEnabled": true,
"ios": { "ios": {
"supportsTablet": true, "supportsTablet": true
"bundleIdentifier": "com.anonymous.mydrawerapp",
"buildNumber": "1.0.0",
"infoPlist": {
"UIBackgroundModes": [
"remote-notification"
],
"NSUserTrackingUsageDescription": "This identifier will be used to deliver personalized notifications.",
"NSUserNotificationUsageDescription": "This app uses notifications to keep you informed."
}
}, },
"android": { "android": {
"adaptiveIcon": { "useNextNotificationsApi": true,
"backgroundColor": "#E6F4FE", "googleServicesFile": "./google-services.json",
"foregroundImage": "./assets/images/android-icon-foreground.png", "adaptiveIcon": {
"backgroundImage": "./assets/images/android-icon-background.png", "backgroundColor": "#E6F4FE",
"monochromeImage": "./assets/images/android-icon-monochrome.png" "foregroundImage": "./assets/images/icon.png"
}, },
"edgeToEdgeEnabled": true, "edgeToEdgeEnabled": true,
"predictiveBackGestureEnabled": false, "predictiveBackGestureEnabled": false,
"package": "com.anonymous.mydrawerapp", "package": "com.gansejunge.notifier"
"versionCode": 1,
"permissions": [
"NOTIFICATIONS"
],
"googleServicesFile": "./google-services.json"
}, },
"web": { "web": {
"output": "static", "output": "static",
"favicon": "./assets/images/favicon.png" "favicon": "./assets/images/icon.png"
}, },
"plugins": [ "plugins": [
"expo-router", "expo-router",
@ -53,15 +39,6 @@
"backgroundColor": "#000000" "backgroundColor": "#000000"
} }
} }
],
[
"expo-notifications",
{
"icon": "./assets/images/notification-icon.png",
"color": "#000000",
"androidMode": "default",
"androidCollapsedTitle": "New notification"
}
] ]
], ],
"experiments": { "experiments": {
@ -71,7 +48,7 @@
"extra": { "extra": {
"router": {}, "router": {},
"eas": { "eas": {
"projectId": "630e211b-f7de-4a82-a863-5962a593f5aa" "projectId": "361036ad-f0cf-41d1-ba27-d3f39f6019dc"
} }
} }
} }

View File

@ -1,144 +0,0 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import * as Notifications from "expo-notifications";
import React, { useEffect, useState } from "react";
import { Linking, ScrollView, Text, TextInput, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Category, categories, categoryKeys, categoryTitles } from "types/Category";
import { Item } from "types/Item";
import { usePushNotifications } from "../hooks/usePushNotifications";
import { styles } from "../styles/HomeScreen.styles";
const API_URL = "https://notifier.gansejunge.com";
const STORAGE_KEY = "notifications";
const API_KEY_STORAGE = "api_key";
export default function HomeScreen() {
const [data, setData] = useState<Item[]>([]);
const [selected, setSelected] = useState<Category>("home");
const [menuOpen, setMenuOpen] = useState(false);
const [apiKey, setApiKey] = useState<string | null>(null);
const [tempKey, setTempKey] = useState("");
const pushToken = usePushNotifications({
apiKey,
backendUrl: API_URL,
appVersion: "1.0.0",
locale: "en-uk",
});
// Load API key on startup
useEffect(() => {
(async () => {
const storedKey = await AsyncStorage.getItem(API_KEY_STORAGE);
if (storedKey) setApiKey(storedKey);
})();
}, []);
// Load saved notifications
useEffect(() => {
(async () => {
try {
const stored = await AsyncStorage.getItem(STORAGE_KEY);
if (stored) setData(JSON.parse(stored));
} catch (err) {
console.error("Failed to load stored notifications:", err);
}
})();
}, []);
// Listen for incoming notifications
useEffect(() => {
const subscription = Notifications.addNotificationReceivedListener(notification => {
const rawCategory = notification.request.content.data?.category as Category | undefined;
const category: Category = rawCategory && categoryKeys.includes(rawCategory) ? rawCategory : "home";
const item: Item = {
timestamp: Date.now(),
category,
title: notification.request.content.title || "No title",
info: notification.request.content.body || "No description",
link: (notification.request.content.data?.link as string) || "#",
};
setData(prev => {
const updated = [...prev, item].sort((a, b) => b.timestamp - a.timestamp);
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
return updated;
});
});
return () => subscription.remove();
}, []);
const filteredData = selected === "home" ? data : data.filter(item => item.category === selected);
const menuItems = categories;
if (!apiKey) {
return (
<SafeAreaView style={styles.container}>
<View style={{ padding: 20 }}>
<Text style={{ marginBottom: 10 }}>Enter API Key:</Text>
<TextInput
value={tempKey}
onChangeText={setTempKey}
style={{ borderWidth: 1, padding: 8, marginBottom: 10 }}
/>
<TouchableOpacity
onPress={async () => {
await AsyncStorage.setItem(API_KEY_STORAGE, tempKey);
setApiKey(tempKey);
}}
style={{ backgroundColor: "blue", padding: 10 }}
>
<Text style={{ color: "white" }}>Save</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container}>
{/* Side Menu */}
<View style={[styles.sideMenu, menuOpen && styles.sideMenuOpen]}>
{menuItems.map(item => (
<TouchableOpacity
key={item.key}
style={[styles.menuItem, selected === item.key && styles.menuItemSelected]}
onPress={() => {
setSelected(item.key);
setMenuOpen(false);
}}
>
<Text style={styles.menuText}>{item.label}</Text>
</TouchableOpacity>
))}
</View>
{/* Main Content */}
<View style={styles.mainContent}>
<TouchableOpacity style={styles.menuButton} onPress={() => setMenuOpen(!menuOpen)}>
<Text style={styles.menuButtonText}></Text>
</TouchableOpacity>
<Text style={styles.title}>{categoryTitles[selected]}</Text>
<ScrollView style={styles.dataContainer}>
{filteredData.length === 0 ? (
<Text style={{ textAlign: "center", marginTop: 20 }}>No items yet</Text>
) : (
filteredData.map(item => (
<View key={`${item.timestamp}-${item.title}`} style={styles.dataItem}>
<Text style={styles.dataTitle}>{item.title}</Text>
<Text style={styles.dataDescription}>{item.info}</Text>
<TouchableOpacity onPress={() => Linking.openURL(item.link)}>
<Text style={{ color: "blue" }}>Read more</Text>
</TouchableOpacity>
</View>
))
)}
</ScrollView>
</View>
</SafeAreaView>
);
}

View File

@ -1,83 +0,0 @@
import React from 'react';
import { Linking, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { Category, categoryTitles } from 'types/Category';
import { Item } from 'types/Item';
type MainContentProps = {
selected: Category;
onToggleMenu: () => void;
data: Item[];
};
export default function MainContent({ selected, onToggleMenu, data }: MainContentProps) {
return (
<View style={styles.mainContent}>
<TouchableOpacity style={styles.menuButton} onPress={onToggleMenu}>
<Text style={styles.menuButtonText}></Text>
</TouchableOpacity>
<Text style={styles.title}>{categoryTitles[selected]}</Text>
<ScrollView style={styles.dataContainer}>
{data.map(item => (
<TouchableOpacity key={`${item.timestamp}-${item.title}`} onPress={() => Linking.openURL(item.link)}>
<View style={styles.dataItem}>
<Text style={styles.dataTitle}>{item.title}</Text>
<Text style={styles.dataDescription}>{item.info}</Text>
</View>
</TouchableOpacity>
))}
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
mainContent: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
position: 'relative',
backgroundColor: '#f2f2f2',
},
menuButton: {
position: 'absolute',
top: 40,
left: 16,
zIndex: 1,
backgroundColor: '#333',
borderRadius: 20,
padding: 8,
},
menuButtonText: {
color: '#fff',
fontSize: 24,
},
title: {
fontSize: 24,
fontWeight: 'bold',
color: '#333',
marginTop: 60,
marginBottom: 16,
},
dataContainer: {
width: '90%',
},
dataItem: {
backgroundColor: '#fff',
borderRadius: 8,
padding: 16,
marginBottom: 12,
boxShadow: '0 2px 4px rgba(0,0,0,0.05)',
},
dataTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#222',
marginBottom: 4,
},
dataDescription: {
fontSize: 15,
color: '#555',
},
});

View File

@ -1,52 +0,0 @@
import React from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
export type MenuItem = {
label: string;
key: string;
};
type SideMenuProps = {
menuItems: MenuItem[];
selected: string;
onSelect: (key: string) => void;
};
export default function SideMenu({ menuItems, selected, onSelect }: SideMenuProps) {
return (
<View style={styles.sideMenu}>
{menuItems.map(item => (
<TouchableOpacity
key={item.key}
style={[
styles.menuItem,
selected === item.key && styles.menuItemSelected,
]}
onPress={() => onSelect(item.key)}>
<Text style={styles.menuText}>{item.label}</Text>
</TouchableOpacity>
))}
</View>
);
}
const styles = StyleSheet.create({
sideMenu: {
width: 180,
backgroundColor: '#333',
paddingTop: 40,
paddingHorizontal: 16,
},
menuItem: {
paddingVertical: 16,
borderRadius: 4,
marginBottom: 8,
},
menuItemSelected: {
backgroundColor: '#555',
},
menuText: {
color: '#fff',
fontSize: 18,
},
});

View File

@ -1,11 +1,208 @@
import React from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage';
import { SafeAreaProvider } from "react-native-safe-area-context"; import { createDrawerNavigator, DrawerContentScrollView, DrawerItemList } from '@react-navigation/drawer';
import HomeScreen from './HomeScreen'; import React, { useEffect, useState } from 'react';
import { Button, Linking, ScrollView, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { STORAGE_KEY, useNotificationListener } from '../hooks/useNotificationListener';
import { usePushNotifications } from '../hooks/usePushNotifications';
import { version as appVersion } from '../package.json';
import { styles } from '../styles/styles';
import { categories, Category, categoryTitles } from '../types/Category';
import { Item } from "../types/Item";
const Drawer = createDrawerNavigator();
const API_KEY_STORAGE = 'API_KEY';
const API_URL = 'https://notifier.gansejunge.com';
type ApiKeyScreenProps = {
onApiKeySaved: (key: string) => void;
};
function ApiKeyScreen({ onApiKeySaved }: ApiKeyScreenProps) {
const [apiKey, setApiKey] = useState('');
const saveApiKey = async () => {
if (apiKey.trim()) {
await AsyncStorage.setItem(API_KEY_STORAGE, apiKey);
onApiKeySaved(apiKey);
}
};
return (
<View style={styles.centered}>
<Text style={styles.label}>Enter your API Key:</Text>
<TextInput
style={[styles.input, { color: '#000', backgroundColor: '#fff' }]}
value={apiKey}
onChangeText={setApiKey}
secureTextEntry
placeholder="API Key"
placeholderTextColor="#030303ff"
/>
<Button title="Save" onPress={saveApiKey} />
</View>
);
}
function CategoryScreen({
category,
notifications,
registered,
registrationError,
}: {
category: Category;
notifications: Item[];
registered: boolean;
registrationError: string | null;
}) {
const [showBanner, setShowBanner] = useState(true);
// Auto-hide banner after 4 seconds whenever it changes
useEffect(() => {
if (!registered && !registrationError) return; // nothing to show
setShowBanner(true); // reset visibility
const timer = setTimeout(() => setShowBanner(false), 4000);
return () => clearTimeout(timer);
}, [registered, registrationError]);
const filtered = category === "home"
? notifications
: notifications.filter(n => n.category === category);
const sorted = filtered.sort((a, b) => b.timestamp - a.timestamp);
const openLink = (url: string) => {
if (url && url !== "#") Linking.openURL(url).catch(console.error);
};
return (
<ScrollView contentContainerStyle={{ padding: 16 }}>
{/* Banner */}
{showBanner && registrationError && (
<View style={{ padding: 8, backgroundColor: "#F44336", borderRadius: 4, marginBottom: 12 }}>
<Text style={{ color: "#fff", textAlign: "center", fontSize: 12 }}>
{registrationError}
</Text>
</View>
)}
<Text style={{ fontSize: 30, marginBottom: 16, color: "#000", textAlign: "center" }}>
{categoryTitles[category]}
</Text>
{sorted.length === 0 ? (
<View style={{ backgroundColor: "#444", padding: 16, borderRadius: 10, alignItems: "center", justifyContent: "center", marginTop: 20 }}>
<Text style={{ color: "#ccc", fontSize: 14 }}>No notifications yet.</Text>
</View>
) : (
sorted.map((item, index) => (
<View key={index} style={{ backgroundColor: "#444", padding: 12, borderRadius: 10, marginBottom: 12 }}>
<Text style={{ color: "#fff", fontWeight: "bold", marginBottom: 4 }}>{item.title}</Text>
<Text style={{ color: "#ccc", fontSize: 12, marginBottom: 4 }}>{new Date(item.timestamp).toLocaleString()}</Text>
<Text style={{ color: "#fff", marginBottom: item.link && item.link !== "#" ? 8 : 0 }}>{item.info}</Text>
{item.link && item.link !== "#" && (
<TouchableOpacity onPress={() => openLink(item.link)}>
<Text style={{ color: "#4da6ff", textDecorationLine: "underline" }}>Click here</Text>
</TouchableOpacity>
)}
</View>
))
)}
</ScrollView>
);
}
// Custom Drawer with Logout at bottom
function CustomDrawerContent({ onLogout, ...props }: any) {
return (
<View style={{ flex: 1, backgroundColor: '#333' }}>
<DrawerContentScrollView {...props} contentContainerStyle={{ paddingTop: 20 }}>
<View style={{ flex: 1, paddingVertical: 10 }}>
<DrawerItemList {...props} />
</View>
</DrawerContentScrollView>
{/* Logout Button */}
<View style={{ padding: 20,paddingBottom: 30, borderTopWidth: 1, borderTopColor: '#444' }}>
<TouchableOpacity onPress={onLogout} style={styles.logoutButton}>
<Text style={styles.logoutText}>Logout</Text>
</TouchableOpacity>
</View>
</View>
);
}
export default function App() { export default function App() {
const [apiKeySaved, setApiKeySaved] = useState<boolean | null>(null);
const [apiKey, setApiKey] = useState<string | null>(null);
const [notifications, setNotifications] = useState<Item[]>([]);
useEffect(() => {
const checkApiKey = async () => {
const key = await AsyncStorage.getItem(API_KEY_STORAGE);
setApiKey(key);
setApiKeySaved(!!key);
};
checkApiKey();
}, []);
const { expoPushToken, registered, registrationError, unregisterToken } = usePushNotifications({
apiKey: apiKey ?? undefined,
backendUrl: API_URL,
appVersion,
locale: 'en-uk',
});
const handleLogout = async () => {
if (unregisterToken) await unregisterToken();
await AsyncStorage.removeItem(API_KEY_STORAGE);
await AsyncStorage.removeItem(STORAGE_KEY);
setApiKey(null);
setApiKeySaved(false);
setNotifications([]);
};
useNotificationListener(setNotifications);
if (apiKeySaved === null) return null;
if (!apiKeySaved) {
return (
<ApiKeyScreen
onApiKeySaved={(key) => {
setApiKey(key);
setApiKeySaved(true);
}}
/>
);
}
return ( return (
<SafeAreaProvider> <Drawer.Navigator
<HomeScreen /> initialRouteName="home"
</SafeAreaProvider> drawerContent={props => <CustomDrawerContent {...props} onLogout={handleLogout} />}
screenOptions={{
headerStyle: { backgroundColor: '#222' },
headerTintColor: '#fff',
drawerStyle: { backgroundColor: '#333', width: 240 },
drawerActiveTintColor: '#fff',
drawerInactiveTintColor: '#ccc',
drawerLabelStyle: { textAlign: 'center', fontSize: 16 },
drawerItemStyle: { paddingVertical: 5, marginVertical: 2 },
}}
>
{categories.map(c => (
<Drawer.Screen key={c.key} name={c.key} options={{ title: c.label }}>
{() => (
< CategoryScreen
category={c.key}
notifications={notifications}
registered={registered}
registrationError={registrationError}
/>
)}
</Drawer.Screen>
))}
</Drawer.Navigator>
); );
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 384 KiB

After

Width:  |  Height:  |  Size: 1.2 MiB

BIN
assets/images/main_menu.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

BIN
assets/images/sidemenu.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 1.2 MiB

View File

@ -1,49 +0,0 @@
{
"name": "my-drawer-app",
"main": "expo-router/entry",
"version": "1.0.0",
"scripts": {
"start": "expo start",
"reset-project": "node ./scripts/reset-project.js",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"lint": "expo lint"
},
"dependencies": {
"@expo/metro-runtime": "~6.1.2",
"@expo/vector-icons": "^15.0.2",
"@react-native-firebase/app": "^23.4.0",
"@react-navigation/bottom-tabs": "^7.4.0",
"@react-navigation/elements": "^2.6.3",
"@react-navigation/native": "^7.1.8",
"expo": "~54.0.10",
"expo-constants": "~18.0.9",
"expo-font": "~14.0.8",
"expo-haptics": "~15.0.7",
"expo-image": "~3.0.8",
"expo-linking": "~8.0.8",
"expo-router": "~6.0.8",
"expo-splash-screen": "~31.0.10",
"expo-status-bar": "~3.0.8",
"expo-symbols": "~1.0.7",
"expo-system-ui": "~6.0.7",
"expo-web-browser": "~15.0.7",
"react": "19.1.0",
"react-dom": "19.1.0",
"react-native": "0.81.4",
"react-native-gesture-handler": "~2.28.0",
"react-native-reanimated": "~4.1.1",
"react-native-safe-area-context": "~5.6.0",
"react-native-screens": "~4.16.0",
"react-native-web": "~0.21.0",
"react-native-worklets": "0.5.1"
},
"devDependencies": {
"@types/react": "~19.1.0",
"eslint": "^9.25.0",
"eslint-config-expo": "~10.0.0",
"typescript": "~5.9.2"
},
"private": true
}

View File

@ -8,7 +8,7 @@
"developmentClient": true, "developmentClient": true,
"distribution": "internal" "distribution": "internal"
}, },
"preview": { "release": {
"android": {"buildType": "apk"} "android": {"buildType": "apk"}
}, },
"debug":{ "debug":{

View File

@ -1,85 +1,207 @@
import AsyncStorage from "@react-native-async-storage/async-storage"; import AsyncStorage from "@react-native-async-storage/async-storage";
import * as Notifications from "expo-notifications"; import * as Notifications from "expo-notifications";
import { useEffect } from "react"; import { useEffect, useRef } from "react";
import { Category, categoryKeys } from "types/Category"; import { Category, categoryKeys } from "../types/Category";
import { Item } from "types/Item"; import { Item } from "../types/Item";
const STORAGE_KEY = "notifications-data"; export const STORAGE_KEY = "notifications-data";
const MAX_STORED_NOTIFICATIONS = 100;
const MAX_AGE_DAYS = 60;
// Simple queue to prevent race conditions
class StorageQueue {
private queue: Array<() => Promise<void>> = [];
private processing = false;
async add(task: () => Promise<void>) {
this.queue.push(task);
if (!this.processing) {
await this.process();
}
}
private async process() {
this.processing = true;
while (this.queue.length > 0) {
const task = this.queue.shift();
if (task) {
try {
await task();
} catch (e) {
console.error("Storage task failed:", e);
}
}
}
this.processing = false;
}
}
const storageQueue = new StorageQueue();
// Hook: listens for incoming notifications → Item + persists them
export function useNotificationListener(onItems: (items: Item[]) => void) { export function useNotificationListener(onItems: (items: Item[]) => void) {
const onItemsRef = useRef(onItems);
const mountedRef = useRef(true);
// Keep ref updated but don't trigger effect re-runs
useEffect(() => { useEffect(() => {
// Load saved notifications on mount onItemsRef.current = onItems;
}, [onItems]);
useEffect(() => {
mountedRef.current = true;
(async () => { (async () => {
try { try {
const saved = await AsyncStorage.getItem(STORAGE_KEY); const saved = await AsyncStorage.getItem(STORAGE_KEY);
if (saved) { let existing: Item[] = saved ? JSON.parse(saved) : [];
const parsed: Item[] = JSON.parse(saved);
// sort newest first // Parse timestamp correctly
onItems(parsed.sort((a, b) => b.timestamp - a.timestamp)); existing = existing.map((i) => ({
...i,
timestamp: Number(i.timestamp),
}));
// Load delivered notifications from the system
const delivered = await Notifications.getPresentedNotificationsAsync?.();
const deliveredItems: Item[] = delivered
?.map(mapNotificationToItem)
.filter((i): i is Item => i !== null) ?? [];
// Combine, deduplicate, and clean
const combined = deduplicateItems([...deliveredItems, ...existing]);
const cleaned = cleanOldItems(combined);
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(cleaned));
if (mountedRef.current) {
onItemsRef.current(cleaned);
} }
} catch (e) { } catch (e) {
console.error("Failed to load notifications from storage:", e); console.error("Failed to load notifications:", e);
} }
})(); })();
// Listen for notification received while app is in foreground
const receivedSub = Notifications.addNotificationReceivedListener(async (notification) => { const receivedSub = Notifications.addNotificationReceivedListener(async (notification) => {
const item = mapNotificationToItem(notification); const item = mapNotificationToItem(notification);
if (item) { if (item && mountedRef.current) {
await addItem(item, onItems); await addItem(item, (items) => {
if (mountedRef.current) {
onItemsRef.current(items);
}
});
} }
}); });
// Listen for when user taps a notification
const responseSub = Notifications.addNotificationResponseReceivedListener(async (response) => { const responseSub = Notifications.addNotificationResponseReceivedListener(async (response) => {
const item = mapNotificationToItem(response.notification); const item = mapNotificationToItem(response.notification);
if (item) { if (item && mountedRef.current) {
await addItem(item, onItems); await addItem(item, (items) => {
if (mountedRef.current) {
onItemsRef.current(items);
}
});
} }
}); });
// Cleanup on unmount
return () => { return () => {
mountedRef.current = false;
receivedSub.remove(); receivedSub.remove();
responseSub.remove(); responseSub.remove();
}; };
}, [onItems]); }, []); // Empty deps - only run once
} }
// Convert Expo notification → Item function normalizeTimestamp(timestamp: any): number {
function mapNotificationToItem(notification: Notifications.Notification): Item | null { const num = Number(timestamp);
if (!num || isNaN(num)) {
return Date.now();
}
// If timestamp appears to be in seconds, convert to milliseconds
if (num < 1000000000000) {
return num * 1000;
}
return num;
}
function generateItemId(item: Item): string {
// Create a unique ID based on timestamp, title, and info
return `${item.timestamp}-${item.title}-${item.info}`.substring(0, 100);
}
function deduplicateItems(items: Item[]): Item[] {
const seen = new Set<string>();
const unique: Item[] = [];
for (const item of items) {
const id = generateItemId(item);
if (!seen.has(id)) {
seen.add(id);
unique.push(item);
}
}
return unique.sort((a, b) => b.timestamp - a.timestamp);
}
function cleanOldItems(items: Item[]): Item[] {
const maxAge = Date.now() - (MAX_AGE_DAYS * 24 * 60 * 60 * 1000);
return items
.filter(item => item.timestamp > maxAge)
.slice(0, MAX_STORED_NOTIFICATIONS);
}
export function mapNotificationToItem(notification: Notifications.Notification): Item | null {
try { try {
const content = notification.request.content; const content = notification.request.content;
const rawCategory = content.data?.category as Category | undefined; const data = content.data || {};
const category: Category = rawCategory && categoryKeys.includes(rawCategory) ? rawCategory : "home";
const rawCategory = data.category as string | undefined;
const category: Category = categoryKeys.includes(rawCategory as Category)
? (rawCategory as Category)
: "utility";
const timestamp = data.timestamp
? normalizeTimestamp(data.timestamp)
: Date.now();
return { return {
timestamp: Date.now(), // could use backend timestamp if provided timestamp,
category, category,
title: content.title ?? "No title", title: content.title ?? "No title",
info: content.body ?? "No details", info: content.body ?? "No description",
link: (content.data?.link as string) ?? "", link: typeof data.link === "string" ? data.link : "#",
}; };
} catch (e) { } catch (err) {
console.error("Failed to map notification to Item:", e); console.error("Failed to map notification to Item:", err);
return null; return null;
} }
} }
export { mapNotificationToItem };
// Save a new item into storage and update state
async function addItem(item: Item, onItems: (items: Item[]) => void) { async function addItem(item: Item, onItems: (items: Item[]) => void) {
try { await storageQueue.add(async () => {
const saved = await AsyncStorage.getItem(STORAGE_KEY); try {
const prev: Item[] = saved ? JSON.parse(saved) : []; const saved = await AsyncStorage.getItem(STORAGE_KEY);
const prev: Item[] = saved ? JSON.parse(saved) : [];
const updated = [item, ...prev].sort((a, b) => b.timestamp - a.timestamp); const combined = [item, ...prev]
.map((i) => ({ ...i, timestamp: Number(i.timestamp) }));
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(updated)); // Deduplicate and clean
onItems(updated); const deduplicated = deduplicateItems(combined);
} catch (e) { const cleaned = cleanOldItems(deduplicated);
console.error("Failed to persist notification:", e);
} await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(cleaned));
onItems(cleaned);
} catch (e) {
console.error("Failed to persist notification:", e);
// Still call onItems with the new item so UI updates even if persistence fails
onItems([item]);
}
});
} }
export default null;

View File

@ -2,6 +2,7 @@ import * as Device from "expo-device";
import * as Notifications from "expo-notifications"; import * as Notifications from "expo-notifications";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Platform } from "react-native"; import { Platform } from "react-native";
import { version as packageVersion } from '../package.json';
type RegisterTokenParams = { type RegisterTokenParams = {
apiKey?: string | null; apiKey?: string | null;
@ -14,46 +15,104 @@ type RegisterTokenParams = {
export function usePushNotifications({ export function usePushNotifications({
apiKey, apiKey,
backendUrl, backendUrl,
appVersion = "1.0.0", appVersion = packageVersion,
locale, locale,
topics topics
}: RegisterTokenParams & { apiKey?: string | null }) { }: RegisterTokenParams & { apiKey?: string | null }) {
const [expoPushToken, setExpoPushToken] = useState<string | null>(null); const [expoPushToken, setExpoPushToken] = useState<string | null>(null);
const [registered, setRegistered] = useState(false);
const [registrationError, setRegistrationError] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
if (!apiKey) return; if (!apiKey) {
console.log("No API key available, skipping registration");
return;
}
const registerTokenWithBackend = async (token: string) => {
console.log("Attempting to register token with backend...");
const res = await fetch(`${backendUrl}/register-token`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": apiKey
},
body: JSON.stringify({
token,
platform: Platform.OS,
app_ver: appVersion,
locale,
topics
})
});
if (!res.ok) {
const errorText = await res.text();
console.error("Backend registration failed:", res.status, errorText);
throw new Error(`Failed to register token: ${res.status}`);
}
console.log("Push token registered with backend ✅");
};
(async () => { (async () => {
const token = await registerForPushNotificationsAsync(); try {
if (token) { const token = await registerForPushNotificationsAsync();
setExpoPushToken(token); if (token) {
await registerTokenWithBackend(token); console.log("Got push token:", token);
setExpoPushToken(token);
await registerTokenWithBackend(token);
setRegistered(true);
setRegistrationError(null);
} else {
console.log("No push token received");
setRegistrationError("Could not get push token");
}
} catch (err) {
console.error("Registration error:", err);
setRegistered(false);
setRegistrationError(err instanceof Error ? err.message : "Failed to register push token");
} }
})(); })();
}, [apiKey]); }, [apiKey, backendUrl, appVersion, locale, topics]);
const unregisterToken = async () => {
if (!expoPushToken || !apiKey) {
console.log("Cannot unregister: missing token or API key");
return;
}
const registerTokenWithBackend = async (token: string) => {
try { try {
await fetch(`${backendUrl}/register_token`, { console.log("Unregistering token from backend...");
const res = await fetch(`${backendUrl}/unregister-token`, {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
"X-API-Key": apiKey ?? "", "X-API-Key": apiKey,
}, },
body: JSON.stringify({ body: JSON.stringify({
token, token: expoPushToken,
platform: Platform.OS, platform: Platform.OS,
app_ver: appVersion, app_ver: appVersion,
locale, locale,
topics topics
}) })
}); });
console.log("Push token registered with backend ✅");
if (!res.ok) {
throw new Error(`Unregister failed: ${res.status}`);
}
console.log("Push token unregistered from backend ✅");
setExpoPushToken(null);
setRegistered(false);
} catch (error) { } catch (error) {
console.error("Failed to register token with backend:", error); console.error("Failed to unregister token:", error);
} }
}; };
return expoPushToken; return { expoPushToken, registered, registrationError, unregisterToken };
} }
async function registerForPushNotificationsAsync() { async function registerForPushNotificationsAsync() {
@ -90,4 +149,4 @@ async function registerForPushNotificationsAsync() {
} }
return token; return token;
} }

7025
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,32 +1,45 @@
{ {
"name": "my-drawer-app", "name": "notifier",
"main": "expo-router/entry", "main": "expo-router/entry",
"version": "1.0.0", "version": "1.0.0",
"scripts": { "scripts": {
"start": "expo start", "start": "expo start",
"reset-project": "node ./scripts/reset-project.js", "android": "expo start --android",
"android": "expo run:android", "ios": "expo start --ios",
"ios": "expo run:ios",
"web": "expo start --web", "web": "expo start --web",
"lint": "expo lint" "lint": "expo lint"
}, },
"dependencies": { "dependencies": {
"@expo/metro-runtime": "~6.1.2", "@expo/vector-icons": "^15.0.2",
"@radix-ui/react-dialog": "^1.1.15", "@react-native-async-storage/async-storage": "^2.2.0",
"@react-native-async-storage/async-storage": "2.2.0", "@react-navigation/bottom-tabs": "^7.4.0",
"expo": "~54.0.11", "@react-navigation/drawer": "^7.5.10",
"@react-navigation/elements": "^2.6.3",
"@react-navigation/native": "^7.1.18",
"eas-cli": "^16.23.0",
"expo": "~54.0.13",
"expo-constants": "~18.0.9", "expo-constants": "~18.0.9",
"expo-device": "~8.0.9", "expo-device": "^8.0.9",
"expo-font": "~14.0.9",
"expo-haptics": "~15.0.7",
"expo-image": "~3.0.9",
"expo-linking": "~8.0.8", "expo-linking": "~8.0.8",
"expo-notifications": "~0.32.12", "expo-notifications": "^0.32.12",
"expo-router": "~6.0.9", "expo-router": "~6.0.11",
"expo-splash-screen": "~31.0.10", "expo-splash-screen": "~31.0.10",
"expo-status-bar": "~3.0.8",
"expo-symbols": "~1.0.7",
"expo-system-ui": "~6.0.7", "expo-system-ui": "~6.0.7",
"react": "^19.2.0", "expo-web-browser": "~15.0.8",
"react-dom": "^19.2.0", "react": "19.1.0",
"react-dom": "19.1.0",
"react-native": "0.81.4", "react-native": "0.81.4",
"react-native-gesture-handler": "~2.28.0",
"react-native-reanimated": "~4.1.1",
"react-native-safe-area-context": "~5.6.0", "react-native-safe-area-context": "~5.6.0",
"react-native-screens": "~4.16.0" "react-native-screens": "~4.16.0",
"react-native-web": "~0.21.0",
"react-native-worklets": "0.5.1"
}, },
"devDependencies": { "devDependencies": {
"@types/react": "~19.1.0", "@types/react": "~19.1.0",

View File

@ -1,79 +0,0 @@
import { StyleSheet } from "react-native";
export const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "row",
backgroundColor: "#f2f2f2",
},
sideMenu: {
width: 0,
backgroundColor: "#333",
paddingTop: 40,
paddingHorizontal: 0,
overflow: "hidden",
},
sideMenuOpen: {
width: 180,
paddingHorizontal: 16,
},
menuItem: {
paddingVertical: 16,
paddingHorizontal: 8,
borderRadius: 4,
marginBottom: 8,
},
menuItemSelected: {
backgroundColor: "#555",
},
menuText: {
color: "#fff",
fontSize: 18,
},
mainContent: {
flex: 1,
justifyContent: "center",
alignItems: "center",
position: "relative",
},
menuButton: {
position: "absolute",
top: 40,
left: 16,
zIndex: 1,
backgroundColor: "#333",
borderRadius: 20,
padding: 8,
},
menuButtonText: {
color: "#fff",
fontSize: 24,
},
title: {
fontSize: 24,
fontWeight: "bold",
marginTop: 60,
color: "#333",
},
dataContainer: {
marginTop: 24,
width: "90%",
},
dataItem: {
backgroundColor: '#fff',
borderRadius: 8,
padding: 16,
marginBottom: 12,
boxShadow: '0 2px 4px rgba(0,0,0,0.05)',
},
dataTitle: {
fontSize: 18,
fontWeight: "bold",
color: "#222",
marginBottom: 4,
},
dataDescription: {
fontSize: 15,
color: "#555",
},
});

35
styles/styles.ts Normal file
View File

@ -0,0 +1,35 @@
import { StyleSheet } from "react-native";
export const styles = StyleSheet.create({
centered: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 16,
backgroundColor: '#fff', // dark background for screens
},
input: {
borderWidth: 1,
borderColor: '#555',
width: '80%',
padding: 8,
marginVertical: 16,
borderRadius: 8,
color: '#fff',
},
label: {
color: '#fff',
fontSize: 16,
},
logoutButton: {
backgroundColor: '#444',
paddingVertical: 12,
borderRadius: 8,
alignItems: 'center',
},
logoutText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
});

View File

@ -5,9 +5,6 @@
"paths": { "paths": {
"@/*": [ "@/*": [
"./*" "./*"
],
"types/*": [
"./types/*"
] ]
} }
}, },

View File

@ -1,6 +1,5 @@
export type Category = "home" | "royal-road" | "podcasts" | "mixtapes" | "utility"; export type Category = "home" | "royal-road" | "podcasts" | "mixtapes" | "utility";
const baseCategories = [ const baseCategories = [
{ key: "home", label: "Home", title: "Welcome to Home!" }, { key: "home", label: "Home", title: "Welcome to Home!" },
{ key: "royal-road", label: "Royal Road", title: "Royal Road Chapters" }, { key: "royal-road", label: "Royal Road", title: "Royal Road Chapters" },
@ -9,7 +8,8 @@ const baseCategories = [
{ key: "utility", label: "Utility", title: "Utility" }, { key: "utility", label: "Utility", title: "Utility" },
] as const; ] as const;
export const categoryKeys: Category[] = baseCategories.map(c => c.key) as Category[];
export const categoryKeys: Category[] = baseCategories.map(c => c.key);
export const categories: { label: string; key: Category }[] = baseCategories.map(c => ({ label: c.label, key: c.key })); export const categories: { label: string; key: Category }[] = baseCategories.map(c => ({ label: c.label, key: c.key }));
export const categoryTitles: Record<Category, string> = Object.fromEntries(baseCategories.map(c => [c.key, c.title])) as Record<Category, string>; export const categoryTitles: Record<Category, string> = Object.fromEntries(baseCategories.map(c => [c.key, c.title])) as Record<Category, string>;
export default Category;