Compare commits
5 Commits
f5f0c63f67
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| da676718d1 | |||
| 88b9f5c387 | |||
| aace4da04a | |||
| e05a2061c4 | |||
| 7b224c6158 |
@@ -0,0 +1,3 @@
|
|||||||
|
NEXT_PUBLIC_VAPID_PUBLIC_KEY=BBVuTTKBNkLp2WCh0mXH-Biy8A50XlAvCcHU5tEJFfuUIDEdKg4gw_evU08KLAGJzgC8iurciHX8Ac_VclRDrJE
|
||||||
|
VAPID_PRIVATE_KEY=7RHcigeLtd48aZReOYVGrQ-KCin1tWMtIwDSqNuM7F8
|
||||||
|
VAPID_SUBJECT_EMAIL="mailto:witel@info.com"
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"Home": {
|
"Home": {
|
||||||
"title": "مرحبا"
|
"title": "مرحبا"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"Home": {
|
"Home": {
|
||||||
"title": "hello"
|
"title": "hello"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"Home": {
|
"Home": {
|
||||||
"title": "سلام"
|
"title": "سلام"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"Home": {
|
"Home": {
|
||||||
"title": "مرحبا"
|
"title": "مرحبا"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
2
next-env.d.ts
vendored
2
next-env.d.ts
vendored
@@ -1,6 +1,6 @@
|
|||||||
/// <reference types="next" />
|
/// <reference types="next" />
|
||||||
/// <reference types="next/image-types/global" />
|
/// <reference types="next/image-types/global" />
|
||||||
import "./.next/dev/types/routes.d.ts";
|
import "./.next/types/routes.d.ts";
|
||||||
|
|
||||||
// NOTE: This file should not be edited
|
// NOTE: This file should not be edited
|
||||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||||
|
|||||||
@@ -1,16 +1,6 @@
|
|||||||
// next.config.ts
|
|
||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
import createNextIntlPlugin from "next-intl/plugin";
|
import createNextIntlPlugin from "next-intl/plugin";
|
||||||
|
|
||||||
// @ts-ignore – no types for next-pwa
|
|
||||||
const withPWA = require("next-pwa")({
|
|
||||||
dest: "public",
|
|
||||||
disable: process.env.NODE_ENV === "development",
|
|
||||||
register: true,
|
|
||||||
skipWaiting: true,
|
|
||||||
navigateFallback: "/offline.html", // fallback page
|
|
||||||
});
|
|
||||||
|
|
||||||
const withNextIntl = createNextIntlPlugin();
|
const withNextIntl = createNextIntlPlugin();
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
@@ -22,4 +12,4 @@ const nextConfig: NextConfig = {
|
|||||||
|
|
||||||
const configWithIntl = withNextIntl(nextConfig);
|
const configWithIntl = withNextIntl(nextConfig);
|
||||||
|
|
||||||
export default withPWA(configWithIntl);
|
export default configWithIntl;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"name": "cinematales",
|
"name": "ruya",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@types/js-cookie": "^3.0.6",
|
"@types/js-cookie": "^3.0.6",
|
||||||
|
"@types/web-push": "^3.6.4",
|
||||||
"axios": "^1.15.0",
|
"axios": "^1.15.0",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
@@ -34,6 +35,7 @@
|
|||||||
"react-hot-toast": "^2.6.0",
|
"react-hot-toast": "^2.6.0",
|
||||||
"tailwind-merge": "^3.5.0",
|
"tailwind-merge": "^3.5.0",
|
||||||
"tailwind-scrollbar": "^4.0.2",
|
"tailwind-scrollbar": "^4.0.2",
|
||||||
|
"web-push": "^3.6.7",
|
||||||
"zustand": "^5.0.12"
|
"zustand": "^5.0.12"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"id": "/",
|
"id": "/",
|
||||||
"name": "Theater of dreams",
|
"name": "Ru'ya",
|
||||||
"short_name": "Theater of dreams",
|
"short_name": "Ru'ya",
|
||||||
"description": "Theater of dreams",
|
"description": "Ru'ya",
|
||||||
"start_url": "/",
|
"start_url": "/",
|
||||||
"display": "standalone",
|
"display": "standalone",
|
||||||
"orientation": "portrait",
|
"orientation": "portrait",
|
||||||
10
public/offline.html
Normal file
10
public/offline.html
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Offline</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>You are offline</h1>
|
||||||
|
<p>Please check your connection.</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
77
public/sw.js
Normal file
77
public/sw.js
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
const CACHE_NAME = "141-cache-v2";
|
||||||
|
|
||||||
|
const STATIC_ASSETS = ["/", "/manifest.webmanifest", "/logo/192px.png", "/logo/512px.png"];
|
||||||
|
|
||||||
|
self.addEventListener("install", (event) => {
|
||||||
|
event.waitUntil(
|
||||||
|
caches.open(CACHE_NAME).then(async (cache) => {
|
||||||
|
await Promise.allSettled(
|
||||||
|
STATIC_ASSETS.map(async (url) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(url);
|
||||||
|
if (response.ok) {
|
||||||
|
await cache.put(url, response);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("❌ Failed to cache:", url);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
self.skipWaiting();
|
||||||
|
});
|
||||||
|
|
||||||
|
const sendDeliveryReportAction = () => {
|
||||||
|
console.log("Web push delivered.");
|
||||||
|
};
|
||||||
|
|
||||||
|
self.addEventListener("push", function (event) {
|
||||||
|
if (event.data) {
|
||||||
|
try {
|
||||||
|
// Try to parse as JSON first
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
data = event.data.json();
|
||||||
|
} catch (jsonError) {
|
||||||
|
// If JSON parsing fails, treat it as plain text
|
||||||
|
const text = event.data.text();
|
||||||
|
data = {
|
||||||
|
title: "Notification",
|
||||||
|
body: text,
|
||||||
|
icon: "/icon.png",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
body: data.body || "Default notification body",
|
||||||
|
icon: data.icon || "/logo/192px.png",
|
||||||
|
badge: "/badge.png",
|
||||||
|
vibrate: [100, 50, 100],
|
||||||
|
data: {
|
||||||
|
dateOfArrival: Date.now(),
|
||||||
|
primaryKey: "2",
|
||||||
|
url: data.url || "/",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
event.waitUntil(
|
||||||
|
self.registration.showNotification(data.title, options).then(() => {
|
||||||
|
sendDeliveryReportAction();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error processing push notification:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
self.addEventListener("notificationclick", function (event) {
|
||||||
|
event.notification.close();
|
||||||
|
event.waitUntil(clients.openWindow(event.notification.data.url));
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener("message", (event) => {
|
||||||
|
if (event.data && event.data.type === "SKIP_WAITING") {
|
||||||
|
self.skipWaiting();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,55 +1,80 @@
|
|||||||
import { getDirection } from "@/i18n/direction";
|
import { getDirection } from "@/i18n/direction";
|
||||||
import { routing } from "@/i18n/routing";
|
import { routing } from "@/i18n/routing";
|
||||||
import { ClientAppProvider } from "@/providers/ClientAppProvider";
|
import { ClientAppProvider } from "@/providers/ClientAppProvider";
|
||||||
import "@/styles/globals.css";
|
import "@/styles/globals.css";
|
||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { hasLocale, NextIntlClientProvider } from "next-intl";
|
import { hasLocale, NextIntlClientProvider } from "next-intl";
|
||||||
import { getMessages } from "next-intl/server";
|
import { getMessages } from "next-intl/server";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "Theater of dreams",
|
title: {
|
||||||
};
|
template: "%s | Ru'ya",
|
||||||
|
default: "Ru'ya",
|
||||||
export default async function RootLayout({
|
},
|
||||||
children,
|
description: "Ru'ya",
|
||||||
params,
|
appleWebApp: {
|
||||||
}: Readonly<{
|
capable: true, // 🔴 REQUIRED for iOS standalone mode
|
||||||
children: React.ReactNode;
|
statusBarStyle: "black-translucent",
|
||||||
params: Promise<{ locale: string }>;
|
title: "Ru'ya",
|
||||||
}>) {
|
},
|
||||||
const { locale } = await params;
|
applicationName: "Ru'ya",
|
||||||
if (!hasLocale(routing.locales, locale)) {
|
authors: {
|
||||||
notFound();
|
name: "شرکت دانش بنیان ویرا ارتباطات یکتا تلفن (وایتل)",
|
||||||
}
|
url: "https://witel.ir",
|
||||||
|
},
|
||||||
const messages = await getMessages();
|
|
||||||
const dir = getDirection(locale);
|
manifest: "/manifest.webmanifest",
|
||||||
|
icons: {
|
||||||
return (
|
icon: "/logo/192px.png",
|
||||||
<html dir={dir} lang={locale} suppressHydrationWarning>
|
apple: "/logo/512px.png",
|
||||||
<head>
|
},
|
||||||
{/* Prevent theme flicker before hydration */}
|
};
|
||||||
<script
|
export const viewport = {
|
||||||
dangerouslySetInnerHTML={{
|
width: "device-width",
|
||||||
__html: `
|
initialScale: 1,
|
||||||
(function() {
|
maximumScale: 1,
|
||||||
try {
|
};
|
||||||
const stored = localStorage.getItem('theme');
|
|
||||||
const theme = stored || 'dark';
|
export default async function RootLayout({
|
||||||
document.documentElement.setAttribute('data-theme', theme);
|
children,
|
||||||
} catch (e) {}
|
params,
|
||||||
})();
|
}: Readonly<{
|
||||||
`,
|
children: React.ReactNode;
|
||||||
}}
|
params: Promise<{ locale: string }>;
|
||||||
/>
|
}>) {
|
||||||
</head>
|
const { locale } = await params;
|
||||||
|
if (!hasLocale(routing.locales, locale)) {
|
||||||
<body className="bg-background">
|
notFound();
|
||||||
<NextIntlClientProvider locale={locale} messages={messages}>
|
}
|
||||||
<ClientAppProvider>{children}</ClientAppProvider>
|
|
||||||
</NextIntlClientProvider>
|
const messages = await getMessages();
|
||||||
</body>
|
const dir = getDirection(locale);
|
||||||
</html>
|
|
||||||
);
|
return (
|
||||||
}
|
<html dir={dir} lang={locale} suppressHydrationWarning>
|
||||||
|
<head>
|
||||||
|
{/* Prevent theme flicker before hydration */}
|
||||||
|
<script
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: `
|
||||||
|
(function() {
|
||||||
|
try {
|
||||||
|
const stored = localStorage.getItem('theme');
|
||||||
|
const theme = stored || 'dark';
|
||||||
|
document.documentElement.setAttribute('data-theme', theme);
|
||||||
|
} catch (e) {}
|
||||||
|
})();
|
||||||
|
`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body className="bg-background">
|
||||||
|
<NextIntlClientProvider locale={locale} messages={messages}>
|
||||||
|
<ClientAppProvider>{children}</ClientAppProvider>
|
||||||
|
</NextIntlClientProvider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
import ComponentsConteiner from "@/components/ComponentsConteiner";
|
import ComponentsConteiner from "@/components/ComponentsConteiner";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const t = useTranslations("Home");
|
const t = useTranslations("Home");
|
||||||
return (
|
return (
|
||||||
<main>
|
<main>
|
||||||
<h1>{t("title")}</h1>
|
<h1>{t("title")}</h1>
|
||||||
<p>This project was generated completely offline.</p>
|
<p>This project was generated completely offline.</p>
|
||||||
<ComponentsConteiner />
|
<ComponentsConteiner />
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,27 +1,27 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import PrimaryButton from "./buttons/PrimaryButton";
|
import PrimaryButton from "./buttons/PrimaryButton";
|
||||||
import ThemeToggle from "./UI/ThemeToggle";
|
import ThemeToggle from "./UI/ThemeToggle";
|
||||||
import { Home } from "lucide-react";
|
import { Home } from "lucide-react";
|
||||||
|
|
||||||
export default function ComponentsConteiner() {
|
export default function ComponentsConteiner() {
|
||||||
const [isLoading, setIsloading] = useState(false);
|
const [isLoading, setIsloading] = useState(false);
|
||||||
function dummyLoading() {
|
function dummyLoading() {
|
||||||
setIsloading(true);
|
setIsloading(true);
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
setIsloading(false);
|
setIsloading(false);
|
||||||
}, 1500);
|
}, 1500);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-start gap-2 p-4">
|
<div className="flex flex-col items-start gap-2 p-4">
|
||||||
<ThemeToggle />
|
<ThemeToggle />
|
||||||
<div className="w-36">
|
<div className="w-36">
|
||||||
<PrimaryButton onClick={() => dummyLoading()} loading={isLoading}>
|
<PrimaryButton onClick={() => dummyLoading()} loading={isLoading}>
|
||||||
<Home size={20} />
|
<Home size={20} />
|
||||||
<p>test icon</p>
|
<p>test icon</p>
|
||||||
</PrimaryButton>
|
</PrimaryButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
139
src/components/PWAPush/PushNotificationManager.tsx
Normal file
139
src/components/PWAPush/PushNotificationManager.tsx
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
function urlBase64ToUint8Array(base64String: string) {
|
||||||
|
// Add padding if needed
|
||||||
|
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
|
||||||
|
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
|
||||||
|
|
||||||
|
const rawData = window.atob(base64);
|
||||||
|
const outputArray = new Uint8Array(rawData.length);
|
||||||
|
|
||||||
|
for (let i = 0; i < rawData.length; ++i) {
|
||||||
|
outputArray[i] = rawData.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return outputArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getUserId(): string {
|
||||||
|
let userId = localStorage.getItem("push_user_id");
|
||||||
|
if (!userId) {
|
||||||
|
userId = `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||||
|
localStorage.setItem("push_user_id", userId);
|
||||||
|
}
|
||||||
|
return userId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function arrayBufferToBase64(buffer: ArrayBuffer | null): string {
|
||||||
|
if (!buffer) return "";
|
||||||
|
const bytes = new Uint8Array(buffer);
|
||||||
|
let binary = "";
|
||||||
|
for (let i = 0; i < bytes.byteLength; i++) {
|
||||||
|
binary += String.fromCharCode(bytes[i]);
|
||||||
|
}
|
||||||
|
return btoa(binary);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AutoPushManager() {
|
||||||
|
useEffect(() => {
|
||||||
|
const initPush = async () => {
|
||||||
|
if (!("serviceWorker" in navigator && "PushManager" in window)) {
|
||||||
|
console.log("Push not supported");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Register service worker
|
||||||
|
const registration = await navigator.serviceWorker.register("/sw.js", {
|
||||||
|
scope: "/",
|
||||||
|
updateViaCache: "none",
|
||||||
|
});
|
||||||
|
|
||||||
|
await navigator.serviceWorker.ready;
|
||||||
|
console.log("Service worker ready");
|
||||||
|
|
||||||
|
// Check existing subscription
|
||||||
|
let subscription = await registration.pushManager.getSubscription();
|
||||||
|
|
||||||
|
if (subscription) {
|
||||||
|
console.log("Already subscribed");
|
||||||
|
// Still register with backend
|
||||||
|
const subscriptionObj = {
|
||||||
|
endpoint: subscription.endpoint,
|
||||||
|
keys: {
|
||||||
|
p256dh: arrayBufferToBase64(subscription.getKey("p256dh")),
|
||||||
|
auth: arrayBufferToBase64(subscription.getKey("auth")),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
await fetch("/api/push-notifications", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
action: "register",
|
||||||
|
userId: getUserId(),
|
||||||
|
subscription: subscriptionObj,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("Push notifications already ready!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check permission status
|
||||||
|
console.log("Current permission:", Notification.permission);
|
||||||
|
|
||||||
|
if (Notification.permission === "denied") {
|
||||||
|
console.log("Notifications are blocked. Please enable them in browser settings.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request permission (this shows the browser prompt)
|
||||||
|
console.log("Requesting permission...");
|
||||||
|
const permission = await Notification.requestPermission();
|
||||||
|
console.log("Permission result:", permission);
|
||||||
|
|
||||||
|
if (permission === "granted") {
|
||||||
|
console.log("Creating subscription...");
|
||||||
|
// This might still take a moment, but should complete
|
||||||
|
subscription = await registration.pushManager.subscribe({
|
||||||
|
userVisibleOnly: true,
|
||||||
|
applicationServerKey: urlBase64ToUint8Array(process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!),
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("Subscription created:", subscription);
|
||||||
|
|
||||||
|
const subscriptionObj = {
|
||||||
|
endpoint: subscription.endpoint,
|
||||||
|
keys: {
|
||||||
|
p256dh: arrayBufferToBase64(subscription.getKey("p256dh")),
|
||||||
|
auth: arrayBufferToBase64(subscription.getKey("auth")),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
await fetch("/api/push-notifications", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
action: "register",
|
||||||
|
userId: getUserId(),
|
||||||
|
subscription: subscriptionObj,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("Push notifications ready! User ID:", getUserId());
|
||||||
|
} else {
|
||||||
|
console.log("Notification permission not granted:", permission);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Push error:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add a small delay to ensure everything is loaded
|
||||||
|
setTimeout(initPush, 1000);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -1,69 +1,69 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { AnimatePresence, motion } from "framer-motion";
|
import { AnimatePresence, motion } from "framer-motion";
|
||||||
import { LoaderPinwheel } from "lucide-react";
|
import { LoaderPinwheel } from "lucide-react";
|
||||||
|
|
||||||
type PrimaryButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
|
type PrimaryButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||||
loading?: boolean;
|
loading?: boolean;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function PrimaryButton({ children, loading, className, onClick }: PrimaryButtonProps) {
|
export default function PrimaryButton({ children, loading, className, onClick }: PrimaryButtonProps) {
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
className={cn(
|
className={cn(
|
||||||
"bg-primary grid w-full place-items-center overflow-hidden rounded-xl px-4 py-2 text-white hover:scale-102 active:scale-98",
|
"bg-primary grid w-full place-items-center overflow-hidden rounded-xl px-4 py-2 text-white hover:scale-102 active:scale-98",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<AnimatePresence mode="wait">
|
<AnimatePresence mode="wait">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<motion.div
|
<motion.div
|
||||||
key={"loading"}
|
key={"loading"}
|
||||||
initial={{
|
initial={{
|
||||||
opacity: 0,
|
opacity: 0,
|
||||||
x: -80,
|
x: -80,
|
||||||
}}
|
}}
|
||||||
animate={{
|
animate={{
|
||||||
opacity: 1,
|
opacity: 1,
|
||||||
x: 0,
|
x: 0,
|
||||||
}}
|
}}
|
||||||
exit={{
|
exit={{
|
||||||
opacity: 0,
|
opacity: 0,
|
||||||
x: -80,
|
x: -80,
|
||||||
}}
|
}}
|
||||||
transition={{
|
transition={{
|
||||||
duration: 0.2,
|
duration: 0.2,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<LoaderPinwheel className="animate-spin" />
|
<LoaderPinwheel className="animate-spin" />
|
||||||
</motion.div>
|
</motion.div>
|
||||||
) : (
|
) : (
|
||||||
<motion.div
|
<motion.div
|
||||||
key="content"
|
key="content"
|
||||||
initial={{
|
initial={{
|
||||||
opacity: 0,
|
opacity: 0,
|
||||||
x: 80,
|
x: 80,
|
||||||
}}
|
}}
|
||||||
animate={{
|
animate={{
|
||||||
opacity: 1,
|
opacity: 1,
|
||||||
x: 0,
|
x: 0,
|
||||||
}}
|
}}
|
||||||
exit={{
|
exit={{
|
||||||
opacity: 0,
|
opacity: 0,
|
||||||
x: 80,
|
x: 80,
|
||||||
}}
|
}}
|
||||||
transition={{
|
transition={{
|
||||||
duration: 0.2,
|
duration: 0.2,
|
||||||
}}
|
}}
|
||||||
className="flex items-center justify-center gap-2"
|
className="flex items-center justify-center gap-2"
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</motion.div>
|
</motion.div>
|
||||||
)}
|
)}
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
export type Direction = "ltr" | "rtl";
|
export type Direction = "ltr" | "rtl";
|
||||||
|
|
||||||
export const localeDirectionMap: Record<string, Direction> = {
|
export const localeDirectionMap: Record<string, Direction> = {
|
||||||
en: "ltr",
|
en: "ltr",
|
||||||
ar: "rtl",
|
ar: "rtl",
|
||||||
ku: "rtl",
|
ku: "rtl",
|
||||||
fa: "rtl",
|
fa: "rtl",
|
||||||
};
|
};
|
||||||
|
|
||||||
export function getDirection(locale: string): Direction {
|
export function getDirection(locale: string): Direction {
|
||||||
return localeDirectionMap[locale] ?? "ltr";
|
return localeDirectionMap[locale] ?? "ltr";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { createNavigation } from 'next-intl/navigation'
|
import { createNavigation } from "next-intl/navigation";
|
||||||
import { routing } from './routing'
|
import { routing } from "./routing";
|
||||||
|
|
||||||
export const { Link, redirect, usePathname, useRouter, getPathname } = createNavigation(routing)
|
export const { Link, redirect, usePathname, useRouter, getPathname } = createNavigation(routing);
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { getRequestConfig } from "next-intl/server";
|
import { getRequestConfig } from "next-intl/server";
|
||||||
import { hasLocale } from "next-intl";
|
import { hasLocale } from "next-intl";
|
||||||
import { routing } from "./routing";
|
import { routing } from "./routing";
|
||||||
|
|
||||||
export default getRequestConfig(async ({ requestLocale }) => {
|
export default getRequestConfig(async ({ requestLocale }) => {
|
||||||
const requested = await requestLocale;
|
const requested = await requestLocale;
|
||||||
const locale = hasLocale(routing.locales, requested) ? requested : routing.defaultLocale;
|
const locale = hasLocale(routing.locales, requested) ? requested : routing.defaultLocale;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
locale,
|
locale,
|
||||||
messages: (await import(`../../messages/${locale}.json`)).default,
|
messages: (await import(`../../messages/${locale}.json`)).default,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { defineRouting } from "next-intl/routing";
|
import { defineRouting } from "next-intl/routing";
|
||||||
|
|
||||||
export const routing = defineRouting({
|
export const routing = defineRouting({
|
||||||
locales: ["en", "ar", "ku", "fa"],
|
locales: ["en", "ar", "ku", "fa"],
|
||||||
defaultLocale: "en",
|
defaultLocale: "en",
|
||||||
localePrefix: "never",
|
localePrefix: "never",
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
'use client'
|
"use client";
|
||||||
|
|
||||||
import { useLocale } from 'next-intl'
|
import { useLocale } from "next-intl";
|
||||||
import { Direction, getDirection } from './direction'
|
import { Direction, getDirection } from "./direction";
|
||||||
|
|
||||||
export function useDirection(): Direction {
|
export function useDirection(): Direction {
|
||||||
const locale = useLocale()
|
const locale = useLocale();
|
||||||
return getDirection(locale)
|
return getDirection(locale);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { clsx, type ClassValue } from 'clsx'
|
import { clsx, type ClassValue } from "clsx";
|
||||||
import { twMerge } from 'tailwind-merge'
|
import { twMerge } from "tailwind-merge";
|
||||||
|
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs))
|
return twMerge(clsx(inputs));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,26 @@ import { useEffect, useState } from "react";
|
|||||||
export function ClientAppProvider({ children }: { children: React.ReactNode }) {
|
export function ClientAppProvider({ children }: { children: React.ReactNode }) {
|
||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if ("serviceWorker" in navigator) {
|
||||||
|
const registerSW = async () => {
|
||||||
|
try {
|
||||||
|
const registration = await navigator.serviceWorker.register("/sw.js", {
|
||||||
|
scope: "/",
|
||||||
|
updateViaCache: "none",
|
||||||
|
});
|
||||||
|
console.log("Service Worker registered successfully:", registration);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Service Worker registration failed:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Register on page load and after navigation
|
||||||
|
registerSW();
|
||||||
|
window.addEventListener("load", registerSW);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
// wait for hydration
|
// wait for hydration
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setMounted(true);
|
setMounted(true);
|
||||||
|
|||||||
16
src/proxy.ts
16
src/proxy.ts
@@ -1,8 +1,8 @@
|
|||||||
import createMiddleware from 'next-intl/middleware'
|
import createMiddleware from "next-intl/middleware";
|
||||||
import { routing } from './i18n/routing'
|
import { routing } from "./i18n/routing";
|
||||||
|
|
||||||
export default createMiddleware(routing)
|
export default createMiddleware(routing);
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: '/((?!api|trpc|_next|_vercel|.*\\..*).*)',
|
matcher: "/((?!api|trpc|_next|_vercel|.*\\..*).*)",
|
||||||
}
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user