add pwa config
This commit is contained in:
22
src/app/api/notifications/route.ts
Normal file
22
src/app/api/notifications/route.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
let notifications = [
|
||||
{
|
||||
id: 1,
|
||||
title: "خوش آمدید",
|
||||
body: "این یک نوتیفیکیشن تستی است",
|
||||
type: "info",
|
||||
created_at: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: "پرداخت موفق",
|
||||
body: "پرداخت شما با موفقیت انجام شد",
|
||||
type: "success",
|
||||
created_at: new Date().toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json(notifications);
|
||||
}
|
||||
41
src/app/api/notifications/sse/route.ts
Normal file
41
src/app/api/notifications/sse/route.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
let counter = 3;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
const data = {
|
||||
id: counter,
|
||||
title: `نوتیفیکیشن جدید ${counter}`,
|
||||
body: "این پیام از SSE اومده",
|
||||
type: ["info", "success", "warning", "error"][counter % 4],
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const payload = `data: ${JSON.stringify(data)}\n\n`;
|
||||
|
||||
controller.enqueue(encoder.encode(payload));
|
||||
counter++;
|
||||
}, 5000);
|
||||
|
||||
req.signal.addEventListener("abort", () => {
|
||||
clearInterval(interval);
|
||||
controller.close();
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
});
|
||||
}
|
||||
175
src/app/api/push-notifications/route.ts
Normal file
175
src/app/api/push-notifications/route.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import webpush from "web-push";
|
||||
|
||||
// Initialize VAPID keys
|
||||
webpush.setVapidDetails(
|
||||
process.env.VAPID_SUBJECT_EMAIL!,
|
||||
process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!,
|
||||
process.env.VAPID_PRIVATE_KEY!
|
||||
);
|
||||
|
||||
// Define the subscription type that matches what web-push expects
|
||||
interface WebPushSubscription {
|
||||
endpoint: string;
|
||||
keys: {
|
||||
p256dh: string;
|
||||
auth: string;
|
||||
};
|
||||
}
|
||||
|
||||
// Store subscriptions in memory with user IDs
|
||||
// In production, replace this with Redis or a database
|
||||
const userSubscriptions: Map<string, WebPushSubscription> = new Map();
|
||||
|
||||
// Save subscription for a specific user
|
||||
async function saveUserSubscription(userId: string, subscription: WebPushSubscription) {
|
||||
userSubscriptions.set(userId, subscription);
|
||||
// In production: save to Redis/Database
|
||||
// await redis.set(`push:${userId}`, JSON.stringify(subscription));
|
||||
}
|
||||
|
||||
// Get subscription for a specific user
|
||||
async function getUserSubscription(userId: string): Promise<WebPushSubscription | null> {
|
||||
return userSubscriptions.get(userId) || null;
|
||||
// In production: get from Redis/Database
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
// Handle different actions
|
||||
const { action, userId, subscription, title, message, icon, url } = body;
|
||||
|
||||
// Action 1: Register/update subscription for a user
|
||||
if (action === "register") {
|
||||
if (!userId || !subscription) {
|
||||
return NextResponse.json({ error: "userId and subscription are required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Validate subscription has required fields
|
||||
if (!subscription.endpoint || !subscription.keys || !subscription.keys.p256dh || !subscription.keys.auth) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid subscription format - missing endpoint or keys" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const webPushSubscription: WebPushSubscription = {
|
||||
endpoint: subscription.endpoint,
|
||||
keys: {
|
||||
p256dh: subscription.keys.p256dh,
|
||||
auth: subscription.keys.auth,
|
||||
},
|
||||
};
|
||||
|
||||
await saveUserSubscription(userId, webPushSubscription);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Subscription registered for user ${userId}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Action 2: Send notification to a specific user
|
||||
if (action === "send") {
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "userId is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
const userSubscription = await getUserSubscription(userId);
|
||||
|
||||
if (!userSubscription) {
|
||||
return NextResponse.json({ error: `No subscription found for user ${userId}` }, { status: 404 });
|
||||
}
|
||||
|
||||
const payload = JSON.stringify({
|
||||
title: title || "Notification",
|
||||
body: message || "You have a new notification",
|
||||
icon: icon || "/logo/192px.png",
|
||||
badge: "/badge.png",
|
||||
vibrate: [100, 50, 100],
|
||||
data: {
|
||||
url: url || "/",
|
||||
dateOfArrival: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
// Send notification using web-push
|
||||
await webpush.sendNotification(userSubscription, payload);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Notification sent to user ${userId}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Action 3: Send to multiple users
|
||||
if (action === "send-multiple") {
|
||||
const { userIds, title, message, icon, url } = body;
|
||||
|
||||
if (!userIds || !Array.isArray(userIds)) {
|
||||
return NextResponse.json({ error: "userIds array is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const uid of userIds) {
|
||||
const userSubscription = await getUserSubscription(uid);
|
||||
|
||||
if (userSubscription) {
|
||||
try {
|
||||
const payload = JSON.stringify({
|
||||
title: title || "Notification",
|
||||
body: message || "You have a new notification",
|
||||
icon: icon || "/logo/192px.png",
|
||||
badge: "/badge.png",
|
||||
data: { url: url || "/" },
|
||||
});
|
||||
|
||||
await webpush.sendNotification(userSubscription, payload);
|
||||
results.push({ userId: uid, status: "success" });
|
||||
} catch (error) {
|
||||
results.push({
|
||||
userId: uid,
|
||||
status: "failed",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
results.push({ userId: uid, status: "no_subscription" });
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
results,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "Invalid action. Use: register, send, or send-multiple" }, { status: 400 });
|
||||
} catch (error) {
|
||||
console.error("Error in push API:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error", details: error instanceof Error ? error.message : String(error) },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// GET endpoint to check if a user is subscribed
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const userId = searchParams.get("userId");
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "userId required" }, { status: 400 });
|
||||
}
|
||||
|
||||
const subscription = await getUserSubscription(userId);
|
||||
|
||||
return NextResponse.json({
|
||||
userId,
|
||||
isSubscribed: !!subscription,
|
||||
});
|
||||
}
|
||||
@@ -6,16 +6,22 @@ import { NextIntlClientProvider } from "next-intl";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: {
|
||||
template: "%s | Theater of dreams",
|
||||
default: "Theater of dreams",
|
||||
template: "%s | Ru'ya",
|
||||
default: "Ru'ya",
|
||||
},
|
||||
description: "Theater of dreams",
|
||||
description: "Ru'ya",
|
||||
appleWebApp: {
|
||||
capable: true, // 🔴 REQUIRED for iOS standalone mode
|
||||
statusBarStyle: "black-translucent",
|
||||
title: "Ru'ya",
|
||||
},
|
||||
applicationName: "Ru'ya",
|
||||
authors: {
|
||||
name: "شرکت دانش بنیان ویرا ارتباطات یکتا تلفن (وایتل)",
|
||||
url: "https://witel.ir",
|
||||
},
|
||||
|
||||
manifest: "/manifest.json",
|
||||
manifest: "/manifest.webmanifest",
|
||||
icons: {
|
||||
icon: "/logo/192px.png",
|
||||
apple: "/logo/512px.png",
|
||||
|
||||
Reference in New Issue
Block a user