Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pwa-subscription #238

Merged
merged 1 commit into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 17 additions & 12 deletions hooks/FcmManger/mutaion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,25 @@ const initializePWAPushService = async () => {
(await navigator.serviceWorker.getRegistration()) ||
(await navigator.serviceWorker.register("/worker.js", { scope: "/" }));

// const registration = await navigator.serviceWorker.register("/worker.js", { scope: "/" });
const subscription = await registration.pushManager.getSubscription();
if (subscription) return;
let subscription = await registration.pushManager.getSubscription();
if (!subscription) {
const publicVapidKey = process.env.NEXT_PUBLIC_PWA_KEY;
if (!publicVapidKey) throw new Error("Missing NEXT_PUBLIC_PWA_KEY");

const publicVapidKey = process.env.NEXT_PUBLIC_PWA_KEY;
if (!publicVapidKey) throw new Error("Missing NEXT_PUBLIC_PWA_KEY");

const newSubscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicVapidKey),
});
subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicVapidKey),
});
console.log("New subscription created.");
} else {
console.log("Existing subscription found.");
}

await registerPushServiceWithPWA(newSubscription);
console.log("Successfully subscribed to push service");
// 서버에 구독 정보 전송
const response = await registerPushServiceWithPWA(subscription);
if (response) {
console.log("Successfully registered push subscription with the server.");
}
} catch (error) {
console.error("Failed to initialize PWA push service:", error);
}
Expand Down
80 changes: 4 additions & 76 deletions pageTemplates/home/HomeInitialSetting.tsx
Original file line number Diff line number Diff line change
@@ -1,93 +1,24 @@
import axios from "axios";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { createGlobalStyle } from "styled-components";

import { USER_GUIDE, USER_LOCATION } from "../../constants/keys/localStorage";
import { SERVER_URI } from "../../constants/system";
import { useToast } from "../../hooks/custom/CustomToast";
import { usePushServiceInitialize } from "../../hooks/FcmManger/mutaion";
import { useUserInfoFieldMutation } from "../../hooks/user/mutations";
import { useUserInfoQuery } from "../../hooks/user/queries";
import FAQPopUp from "../../modals/pop-up/FAQPopUp";
import UserSettingPopUp from "../../pageTemplates/setting/userSetting/userSettingPopUp";
import { isPWA } from "../../utils/appEnvUtils";
import { checkAndSetLocalStorage } from "../../utils/storageUtils";

const urlBase64ToUint8Array = (base64String) => {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");

let rawData;
try {
rawData = window.atob(base64);
} catch (e) {
console.error("Failed to decode base64 string:", e);
throw new Error("The string to be decoded is not correctly encoded.");
}

const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}

return outputArray;
};

const requestAndSubscribePushService = async () => {
const hasPermission = await requestNotificationPermission();
if (!hasPermission) {
return;
}

await subscribePushService({
onSuccess: () => {
console.log("Subscribe push service successfully");
},
});
};

const requestNotificationPermission = async () => {
if (Notification.permission === "granted") {
return true;
}
if (Notification.permission !== "denied") {
const permission = await Notification.requestPermission();
return permission === "granted";
}

return false;
};

const subscribePushService = async (options: { onSuccess?: () => void } = {}) => {
try {
const registration = await navigator.serviceWorker.getRegistration();
const hasSubscription = await registration.pushManager.getSubscription();

if (hasSubscription) {
return;
}

const publicVapidKey = process.env.NEXT_PUBLIC_PWA_KEY;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicVapidKey),
});

await axios.post(`${SERVER_URI}/webpush/subscribe`, subscription);

options.onSuccess?.();
} catch (err) {
console.error(err);
}
};

function HomeInitialSetting() {
const { data: session } = useSession();

// usePushServiceInitialize({
// uid: session?.user?.uid,
// });
usePushServiceInitialize({
uid: session?.user?.uid,
});

const router = useRouter();
const toast = useToast();
Expand Down Expand Up @@ -174,9 +105,6 @@ function HomeInitialSetting() {
// useEffect(() => {
// requestAndSubscribePushService();
// }, []);
useEffect(() => {
requestAndSubscribePushService();
}, []);

// const handleJoyrideCallback = (data: CallBackProps) => {
// if (data.step.target === ".about_navigation1") {
Expand Down
Loading