working push notifiations
This commit is contained in:
@@ -10,6 +10,8 @@ export const users = pgTable('users', {
|
||||
passwordHash: text('password_hash').notNull(),
|
||||
resetToken: text('reset_token'),
|
||||
resetTokenExpiry: bigint('reset_token_expiry', { mode: 'number' }),
|
||||
expoPushToken: text('expo_push_token'),
|
||||
pushTokenUpdatedAt: bigint('push_token_updated_at', { mode: 'number' }),
|
||||
createdAt: bigint('created_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
});
|
||||
|
||||
@@ -86,6 +88,7 @@ export const subtasks = pgTable('subtasks', {
|
||||
taskId: text('task_id').notNull().references(() => tasks.id, { onDelete: 'cascade' }),
|
||||
parentSubtaskId: text('parent_subtask_id').references((): AnyPgColumn => subtasks.id, { onDelete: 'cascade' }),
|
||||
categoryId: text('category_id').references(() => categories.id, { onDelete: 'set null' }),
|
||||
tags: text('tags').notNull().default(''),
|
||||
title: text('title').notNull(),
|
||||
description: text('description').notNull().default(''),
|
||||
priority: text('priority', { enum: ['none', 'low', 'medium', 'high', 'critical'] }).notNull().default('none'),
|
||||
|
||||
@@ -9,6 +9,7 @@ import userRoutes from './routes/users';
|
||||
import friendRoutes from './routes/friends';
|
||||
import repeatProfileRoutes from './routes/repeatProfiles';
|
||||
import syncRoutes from './routes/sync';
|
||||
import pushNotificationRoutes from './routes/pushNotifications';
|
||||
import { errorHandler, notFoundHandler } from './middleware/errorHandler';
|
||||
|
||||
const app = express();
|
||||
@@ -34,6 +35,7 @@ app.use('/api/users', userRoutes);
|
||||
app.use('/api/repeat-profiles', repeatProfileRoutes);
|
||||
app.use('/api/sync', syncRoutes);
|
||||
app.use('/api/friends', friendRoutes);
|
||||
app.use('/api/push', pushNotificationRoutes);
|
||||
|
||||
// 404 handler
|
||||
app.use(notFoundHandler);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { asyncHandler } from '../utils/asyncHandler';
|
||||
import { db } from '../db';
|
||||
import { users } from '../db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { AppError } from '../middleware/errorHandler';
|
||||
import { z } from 'zod';
|
||||
import { sendPushNotification, isExpoPushToken, createTaskReminderPayload } from '../services/pushNotifications';
|
||||
|
||||
const router = Router();
|
||||
|
||||
const registerPushTokenSchema = z.object({
|
||||
pushToken: z.string().min(1),
|
||||
});
|
||||
|
||||
router.post('/push-token', asyncHandler(async (req: Request, res: Response) => {
|
||||
if (!req.user) {
|
||||
throw new AppError('UNAUTHORIZED', 'Authentication required', 401);
|
||||
}
|
||||
|
||||
const data = registerPushTokenSchema.parse(req.body);
|
||||
|
||||
if (!isExpoPushToken(data.pushToken)) {
|
||||
throw new AppError('INVALID_PUSH_TOKEN', 'Invalid Expo push token format', 400);
|
||||
}
|
||||
|
||||
await db
|
||||
.update(users)
|
||||
.set({
|
||||
expoPushToken: data.pushToken,
|
||||
pushTokenUpdatedAt: Date.now(),
|
||||
})
|
||||
.where(eq(users.id, req.user.userId));
|
||||
|
||||
res.json({ success: true });
|
||||
}));
|
||||
|
||||
router.delete('/push-token', asyncHandler(async (req: Request, res: Response) => {
|
||||
if (!req.user) {
|
||||
throw new AppError('UNAUTHORIZED', 'Authentication required', 401);
|
||||
}
|
||||
|
||||
await db
|
||||
.update(users)
|
||||
.set({
|
||||
expoPushToken: null,
|
||||
pushTokenUpdatedAt: Date.now(),
|
||||
})
|
||||
.where(eq(users.id, req.user.userId));
|
||||
|
||||
res.json({ success: true });
|
||||
}));
|
||||
|
||||
router.post('/test', asyncHandler(async (req: Request, res: Response) => {
|
||||
if (!req.user) {
|
||||
throw new AppError('UNAUTHORIZED', 'Authentication required', 401);
|
||||
}
|
||||
|
||||
const user = await db.select().from(users).where(eq(users.id, req.user.userId)).limit(1);
|
||||
if (user.length === 0 || !user[0].expoPushToken) {
|
||||
throw new AppError('NO_PUSH_TOKEN', 'No push token registered', 400);
|
||||
}
|
||||
|
||||
const ticket = await sendPushNotification({
|
||||
to: user[0].expoPushToken!,
|
||||
title: 'Test Notification',
|
||||
body: 'Push notifications are working!',
|
||||
data: { type: 'test' },
|
||||
sound: 'default',
|
||||
});
|
||||
|
||||
res.json({ success: true, ticket });
|
||||
}));
|
||||
|
||||
router.post('/send-reminder', asyncHandler(async (req: Request, res: Response) => {
|
||||
if (!req.user) {
|
||||
throw new AppError('UNAUTHORIZED', 'Authentication required', 401);
|
||||
}
|
||||
|
||||
const { taskId, taskTitle, dueTime, repeat } = req.body;
|
||||
if (!taskId || !taskTitle || !dueTime) {
|
||||
throw new AppError('INVALID_PAYLOAD', 'Missing required fields', 400);
|
||||
}
|
||||
|
||||
const user = await db.select().from(users).where(eq(users.id, req.user.userId)).limit(1);
|
||||
if (user.length === 0 || !user[0].expoPushToken) {
|
||||
throw new AppError('NO_PUSH_TOKEN', 'No push token registered', 400);
|
||||
}
|
||||
|
||||
const ticket = await sendPushNotification(
|
||||
createTaskReminderPayload(user[0].expoPushToken!, taskTitle, dueTime, taskId, repeat)
|
||||
);
|
||||
|
||||
res.json({ success: true, ticket });
|
||||
}));
|
||||
|
||||
export default router;
|
||||
@@ -83,6 +83,7 @@ router.post('/task/:taskId', asyncHandler(async (req: Request, res: Response) =>
|
||||
taskId: req.params.taskId,
|
||||
parentSubtaskId,
|
||||
categoryId: data.categoryId ?? null,
|
||||
tags: data.tags ?? '',
|
||||
title: data.title,
|
||||
description: data.description ?? '',
|
||||
priority: data.priority ?? 'none',
|
||||
|
||||
+34
-46
@@ -17,60 +17,47 @@ router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
|
||||
const sinceDate = since;
|
||||
|
||||
// Fetch categories changed since timestamp
|
||||
const changedCategories = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.userId, userId), gte(categories.updatedAt, sinceDate)))
|
||||
.orderBy(asc(categories.updatedAt));
|
||||
// Fetch all changed entities in parallel
|
||||
const [changedCategories, changedTasks, changedSubtasks, changedRepeatProfiles, changedFriendships, changedTombstones] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.userId, userId), gte(categories.updatedAt, sinceDate)))
|
||||
.orderBy(asc(categories.updatedAt)),
|
||||
|
||||
// Fetch tasks changed since timestamp
|
||||
const changedTasks = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.userId, userId), gte(tasks.updatedAt, sinceDate)))
|
||||
.orderBy(asc(tasks.updatedAt));
|
||||
db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.userId, userId), gte(tasks.updatedAt, sinceDate)))
|
||||
.orderBy(asc(tasks.updatedAt)),
|
||||
|
||||
// Fetch subtasks changed since timestamp
|
||||
let changedSubtasks: any[] = [];
|
||||
if (changedTasks.length > 0) {
|
||||
changedSubtasks = await db
|
||||
db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.userId, userId), gte(subtasks.updatedAt, sinceDate)))
|
||||
.orderBy(asc(subtasks.updatedAt));
|
||||
} else {
|
||||
// Also fetch subtasks for tasks that might have been deleted
|
||||
changedSubtasks = await db
|
||||
.orderBy(asc(subtasks.updatedAt)),
|
||||
|
||||
db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.userId, userId), gte(subtasks.updatedAt, sinceDate)))
|
||||
.orderBy(asc(subtasks.updatedAt));
|
||||
}
|
||||
.from(repeatProfiles)
|
||||
.where(and(eq(repeatProfiles.userId, userId), gte(repeatProfiles.updatedAt, sinceDate)))
|
||||
.orderBy(asc(repeatProfiles.updatedAt)),
|
||||
|
||||
// Fetch repeat profiles changed since timestamp
|
||||
const changedRepeatProfiles = await db
|
||||
.select()
|
||||
.from(repeatProfiles)
|
||||
.where(and(eq(repeatProfiles.userId, userId), gte(repeatProfiles.updatedAt, sinceDate)))
|
||||
.orderBy(asc(repeatProfiles.updatedAt));
|
||||
db
|
||||
.select()
|
||||
.from(friendships)
|
||||
.where(and(
|
||||
or(eq(friendships.userId, userId), eq(friendships.friendId, userId)),
|
||||
gte(friendships.updatedAt, sinceDate)
|
||||
))
|
||||
.orderBy(asc(friendships.updatedAt)),
|
||||
|
||||
// Fetch friendships changed since timestamp
|
||||
const changedFriendships = await db
|
||||
.select()
|
||||
.from(friendships)
|
||||
.where(and(
|
||||
or(eq(friendships.userId, userId), eq(friendships.friendId, userId)),
|
||||
gte(friendships.updatedAt, sinceDate)
|
||||
))
|
||||
.orderBy(asc(friendships.updatedAt));
|
||||
|
||||
// Fetch tombstones (deletions) changed since timestamp
|
||||
const changedTombstones = await db
|
||||
.select()
|
||||
.from(tombstones)
|
||||
.where(and(eq(tombstones.userId, userId), gte(tombstones.updatedAt, sinceDate)))
|
||||
.orderBy(asc(tombstones.updatedAt));
|
||||
db
|
||||
.select()
|
||||
.from(tombstones)
|
||||
.where(and(eq(tombstones.userId, userId), gte(tombstones.updatedAt, sinceDate)))
|
||||
.orderBy(asc(tombstones.updatedAt)),
|
||||
]);
|
||||
|
||||
const timestamp = Date.now();
|
||||
|
||||
@@ -292,6 +279,7 @@ router.post('/push', asyncHandler(async (req: Request, res: Response) => {
|
||||
taskId: sub.taskId,
|
||||
parentSubtaskId: sub.parentSubtaskId ?? null,
|
||||
categoryId: sub.categoryId ?? null,
|
||||
tags: sub.tags ?? '',
|
||||
title: sub.title,
|
||||
description: sub.description ?? '',
|
||||
priority: sub.priority ?? 'none',
|
||||
|
||||
@@ -161,6 +161,7 @@ router.post('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
taskId,
|
||||
title: st.title,
|
||||
categoryId: (st as any).categoryId ?? null,
|
||||
tags: (st as any).tags ?? '',
|
||||
completed: false,
|
||||
order: index,
|
||||
createdAt: now,
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import fetch from 'node-fetch';
|
||||
|
||||
const EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send';
|
||||
|
||||
export interface PushNotificationPayload {
|
||||
to: string;
|
||||
title: string;
|
||||
body: string;
|
||||
data?: Record<string, any>;
|
||||
sound?: string;
|
||||
badge?: number;
|
||||
priority?: 'default' | 'normal' | 'high';
|
||||
channelId?: string;
|
||||
}
|
||||
|
||||
export interface PushTicket {
|
||||
id: string;
|
||||
status: 'ok' | 'error';
|
||||
message?: string;
|
||||
details?: {
|
||||
error?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface PushReceipt {
|
||||
status: 'ok' | 'error';
|
||||
message?: string;
|
||||
details?: {
|
||||
error?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface ExpoPushResponse {
|
||||
data?: PushTicket[] | Record<string, PushReceipt>;
|
||||
}
|
||||
|
||||
export async function sendPushNotification(payload: PushNotificationPayload): Promise<PushTicket> {
|
||||
const response = await fetch(EXPO_PUSH_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
const result = (await response.json()) as ExpoPushResponse;
|
||||
if (result.data && Array.isArray(result.data)) {
|
||||
return result.data[0] ?? { id: '', status: 'error', message: 'No ticket returned' };
|
||||
}
|
||||
return { id: '', status: 'error', message: 'No ticket returned' };
|
||||
}
|
||||
|
||||
export async function sendPushNotifications(payloads: PushNotificationPayload[]): Promise<PushTicket[]> {
|
||||
const chunks: PushNotificationPayload[][] = [];
|
||||
for (let i = 0; i < payloads.length; i += 100) {
|
||||
chunks.push(payloads.slice(i, i + 100));
|
||||
}
|
||||
|
||||
const tickets: PushTicket[] = [];
|
||||
for (const chunk of chunks) {
|
||||
const response = await fetch(EXPO_PUSH_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify(chunk),
|
||||
});
|
||||
const result = (await response.json()) as ExpoPushResponse;
|
||||
if (result.data && Array.isArray(result.data)) {
|
||||
tickets.push(...result.data);
|
||||
}
|
||||
}
|
||||
return tickets;
|
||||
}
|
||||
|
||||
export async function getPushReceipts(ticketIds: string[]): Promise<PushReceipt[]> {
|
||||
if (ticketIds.length === 0) return [];
|
||||
|
||||
const response = await fetch(`${EXPO_PUSH_URL}/receipts`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ ids: ticketIds }),
|
||||
});
|
||||
|
||||
const result = (await response.json()) as ExpoPushResponse;
|
||||
const receipts: PushReceipt[] = [];
|
||||
if (result.data && !Array.isArray(result.data)) {
|
||||
for (const id of ticketIds) {
|
||||
receipts.push(result.data[id] ?? { status: 'error', message: 'No receipt found' });
|
||||
}
|
||||
}
|
||||
return receipts;
|
||||
}
|
||||
|
||||
export function isExpoPushToken(token: string): boolean {
|
||||
return token.startsWith('ExponentPushToken[') || token.startsWith('ExpoPushToken[');
|
||||
}
|
||||
|
||||
export function createTaskReminderPayload(
|
||||
pushToken: string,
|
||||
taskTitle: string,
|
||||
dueTime: string,
|
||||
taskId: string,
|
||||
repeat?: string
|
||||
): PushNotificationPayload {
|
||||
return {
|
||||
to: pushToken,
|
||||
title: taskTitle,
|
||||
body: `Due ${dueTime}${repeat && repeat !== 'none' ? ' · repeating' : ''}`,
|
||||
data: { type: 'task_reminder', taskId },
|
||||
sound: 'default',
|
||||
priority: 'high',
|
||||
channelId: 'task-reminders',
|
||||
};
|
||||
}
|
||||
|
||||
export function createFriendRequestPayload(
|
||||
pushToken: string,
|
||||
fromUsername: string,
|
||||
friendshipId: string
|
||||
): PushNotificationPayload {
|
||||
return {
|
||||
to: pushToken,
|
||||
title: 'New Friend Request',
|
||||
body: `${fromUsername} wants to be your friend`,
|
||||
data: { type: 'friend_request', friendshipId },
|
||||
sound: 'default',
|
||||
priority: 'high',
|
||||
channelId: 'friend-requests',
|
||||
};
|
||||
}
|
||||
|
||||
export function createTaskAssignmentPayload(
|
||||
pushToken: string,
|
||||
taskTitle: string,
|
||||
fromUsername: string,
|
||||
taskId: string
|
||||
): PushNotificationPayload {
|
||||
return {
|
||||
to: pushToken,
|
||||
title: 'Task Assigned',
|
||||
body: `${fromUsername} assigned you "${taskTitle}"`,
|
||||
data: { type: 'task_assignment', taskId },
|
||||
sound: 'default',
|
||||
priority: 'high',
|
||||
channelId: 'task-assignments',
|
||||
};
|
||||
}
|
||||
@@ -75,6 +75,7 @@ export const subtaskCreateSchema = z.object({
|
||||
title: z.string().min(1).max(100),
|
||||
description: z.string().max(1000).optional(),
|
||||
categoryId: z.string().max(100).nullable().optional().transform((v) => (v === '' ? null : v)),
|
||||
tags: z.string().max(500).optional(),
|
||||
priority: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional(),
|
||||
dueDate: z.number().int().min(0).optional(),
|
||||
dueTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional().or(z.literal('')).transform(v => v ?? ''),
|
||||
@@ -95,6 +96,7 @@ export const subtaskUpdateSchema = z.object({
|
||||
title: z.string().min(1).max(100).optional(),
|
||||
description: z.string().max(1000).optional(),
|
||||
categoryId: z.string().max(100).nullable().optional().transform((v) => (v === '' ? null : v)),
|
||||
tags: z.string().max(500).optional(),
|
||||
priority: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional(),
|
||||
completed: z.boolean().optional(),
|
||||
dueDate: z.number().int().min(0).optional(),
|
||||
|
||||
Reference in New Issue
Block a user