diff --git a/public/firebase-messaging-sw.js b/public/firebase-messaging-sw.js index 9b209274..caba954f 100644 --- a/public/firebase-messaging-sw.js +++ b/public/firebase-messaging-sw.js @@ -2,8 +2,12 @@ // See `Access registration token section` @ https://firebase.google.com/docs/cloud-messaging/js/client#retrieve-the-current-registration-token // Scripts for firebase and firebase messaging -importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js"); -importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js"); +importScripts( + "https://www.gstatic.com/firebasejs/9.6.10/firebase-app-compat.js" +); +importScripts( + "https://www.gstatic.com/firebasejs/9.6.10/firebase-messaging-compat.js" +); // Initialize the Firebase app in the service worker by passing the generated config const firebaseConfig = { @@ -34,22 +38,6 @@ messaging.onBackgroundMessage((payload) => { self.registration.showNotification(notificationTitle, notificationOptions); }); -// setTimeout(() => { -// console.log("notification test"); -// self.registration.showNotification("hello", { body: "test" }); -// }, 5000); -// 开始监听推送 -// self.addEventListener("push", function (event) { -// var data = event.data.json(); - -// const title = data.Title; -// data.Data.actions = data.Actions; -// const options = { -// body: data.Message, -// data: data.Data, -// }; -// event.waitUntil(self.registration.showNotification(title, options)); -// }); self.addEventListener("notificationclick", function (event) { console.log("notification click", event, event.notification); @@ -86,27 +74,6 @@ self.addEventListener("notificationclick", function (event) { firstClient.postMessage({ newPath: redirectPath }); firstClient.focus(); } - - // // Let's see if we already have a chat window open: - // for (const client of allClients) { - // const url = new URL(client.url); - - // if (url.pathname == '/chat/') { - // // Excellent, let's use it! - // client.focus(); - // chatClient = client; - // break; - // } - // } - - // // If we didn't find an existing chat window, - // // open a new one: - // if (!chatClient) { - // chatClient = await clients.openWindow('/chat/'); - // } - - // // Message the client: - // chatClient.postMessage("New chat messages!"); })() ); }); diff --git a/src/app/config.js b/src/app/config.js index f8afdc13..fbd4c907 100644 --- a/src/app/config.js +++ b/src/app/config.js @@ -1,6 +1,6 @@ // const BASE_URL = `${location.origin}/api`; const BASE_URL = `https://dev.rustchat.com/api`; -export const CACHE_VERSION = `0.3.1`; +export const CACHE_VERSION = `0.3.2`; // const BASE_URL = `https://rustchat.net/api`; export const ContentTypes = { text: "text/plain", @@ -11,6 +11,16 @@ export const ContentTypes = { formData: "multipart/form-data", json: "application/json", }; +export const firebaseConfig = { + apiKey: "AIzaSyDyJ6B1Ouenoha_gdGkBwIkBNStlwhlbO0", + authDomain: "rustchat-develop.firebaseapp.com", + projectId: "rustchat-develop", + storageBucket: "rustchat-develop.appspot.com", + messagingSenderId: "418687074928", + appId: "1:418687074928:web:753286adbf239f5af9eab5", + measurementId: "G-XV476KEC8P", +}; +export const vapidKey = `BGXCn-5YRXSFw38Q9lUKJ5bibL212-yIQn1pCvthGhp6_KwA29FO1Ax_d_7if1vfC2a5wTSVO8AcZrc-Hm1aS0Y`; export const googleClientID = "418687074928-naojba82n9ktf0rkvnqoor4nhr54ql1b.apps.googleusercontent.com"; // "840319286941-6ds7lbvk55eq8mjortf68cb2ll65lprt.apps.googleusercontent.com"; diff --git a/src/common/component/FirebaseNotification.js b/src/common/component/FirebaseNotification.js deleted file mode 100644 index 01853cf0..00000000 --- a/src/common/component/FirebaseNotification.js +++ /dev/null @@ -1,51 +0,0 @@ -import { useEffect } from "react"; -import { getMessaging, getToken } from "firebase/messaging"; - -// // Import the functions you need from the SDKs you need -// import { initializeApp } from "firebase/app"; -// import { getAnalytics } from "firebase/analytics"; -// // TODO: Add SDKs for Firebase products that you want to use -// // https://firebase.google.com/docs/web/setup#available-libraries - -// // Your web app's Firebase configuration -// // For Firebase JS SDK v7.20.0 and later, measurementId is optional -// const firebaseConfig = { -// apiKey: "AIzaSyDyJ6B1Ouenoha_gdGkBwIkBNStlwhlbO0", -// authDomain: "rustchat-develop.firebaseapp.com", -// projectId: "rustchat-develop", -// storageBucket: "rustchat-develop.appspot.com", -// messagingSenderId: "418687074928", -// appId: "1:418687074928:web:7ad57a83f756285cf9eab5", -// measurementId: "G-61T6TLQ27T" -// }; - -// // Initialize Firebase -// const app = initializeApp(firebaseConfig); -// const analytics = getAnalytics(app); - -export default function Notification() { - useEffect(() => { - // Get registration token. Initially this makes a network call, once retrieved - // subsequent calls to getToken will return from cache. - const messaging = getMessaging(); - getToken(messaging, { vapidKey: "" }) - .then((currentToken) => { - if (currentToken) { - // Send the token to your server and update the UI if necessary - // ... - } else { - // Show permission request UI - console.log( - "No registration token available. Request permission to generate one." - ); - // ... - } - }) - .catch((err) => { - console.log("An error occurred while retrieving token. ", err); - // ... - }); - }, []); - - return
Notification
; -} diff --git a/src/common/component/Notification/firebase.js b/src/common/component/Notification/firebase.js deleted file mode 100644 index 582b4685..00000000 --- a/src/common/component/Notification/firebase.js +++ /dev/null @@ -1,54 +0,0 @@ -// Firebase Cloud Messaging Configuration File. -// Read more at https://firebase.google.com/docs/cloud-messaging/js/client && https://firebase.google.com/docs/cloud-messaging/js/receive -import { useState } from "react"; -import { initializeApp } from "firebase/app"; -import { getMessaging, getToken, onMessage } from "firebase/messaging"; -const firebaseConfig = { - apiKey: "AIzaSyDyJ6B1Ouenoha_gdGkBwIkBNStlwhlbO0", - authDomain: "rustchat-develop.firebaseapp.com", - projectId: "rustchat-develop", - storageBucket: "rustchat-develop.appspot.com", - messagingSenderId: "418687074928", - appId: "1:418687074928:web:753286adbf239f5af9eab5", - measurementId: "G-XV476KEC8P", -}; - -initializeApp(firebaseConfig); - -const messaging = getMessaging(); - -export const useDeviceToken = (vapidKey) => { - const [token, setToken] = useState(null); - - getToken(messaging, { - vapidKey, - }) - .then((currentToken) => { - if (currentToken) { - console.log("current token for client: ", currentToken); - setToken(currentToken); - // updateDeviceToken(currentToken) - // Perform any other neccessary action with the token - } else { - // Show permission request UI - console.log( - "No registration token available. Request permission to generate one." - ); - } - }) - .catch((err) => { - console.log("An error occurred while retrieving token. ", err); - }); - return token; -}; - -// Handle incoming messages. Called when: -// - a message is received while the app has focus -// - the user clicks on an app notification created by a service worker `messaging.onBackgroundMessage` handler. -export const onMessageListener = () => - new Promise((resolve) => { - onMessage(messaging, (payload) => { - console.log("notification payload", payload); - resolve(payload); - }); - }); diff --git a/src/common/component/Notification/index.js b/src/common/component/Notification/index.js index 946f1a53..50860527 100644 --- a/src/common/component/Notification/index.js +++ b/src/common/component/Notification/index.js @@ -1,25 +1,14 @@ -import { useState, useEffect } from "react"; +import { useEffect } from "react"; import { useNavigate } from "react-router-dom"; // import toast, { Toaster } from 'react-hot-toast'; -import { useDeviceToken, onMessageListener } from "./firebase"; +import useDeviceToken from "./useDeviceToken"; +import { vapidKey } from "../../../app/config"; import { useUpdateDeviceTokenMutation } from "../../../app/services/auth"; const Notification = () => { const navigateTo = useNavigate(); - const token = useDeviceToken( - `BGXCn-5YRXSFw38Q9lUKJ5bibL212-yIQn1pCvthGhp6_KwA29FO1Ax_d_7if1vfC2a5wTSVO8AcZrc-Hm1aS0Y` - ); + const token = useDeviceToken(vapidKey); const [updateDeviceToken] = useUpdateDeviceTokenMutation(); - const [notification, setNotification] = useState({ title: "", body: "" }); - // const notify = () => toast(); - // function ToastDisplay() { - // return ( - //
- //

{notification?.title}

- //

{notification?.body}

- //
- // ); - // }; useEffect(() => { if (token) { updateDeviceToken(token); @@ -41,17 +30,7 @@ const Notification = () => { handleServiceworkerMessage ); }; - }, [notification]); - - onMessageListener() - .then((payload) => { - console.log("foreground notification", payload); - setNotification({ - title: payload?.notification?.title, - body: payload?.notification?.body, - }); - }) - .catch((err) => console.log("failed: ", err)); + }, []); return null; }; diff --git a/src/common/component/Notification/useDeviceToken.js b/src/common/component/Notification/useDeviceToken.js new file mode 100644 index 00000000..4c314252 --- /dev/null +++ b/src/common/component/Notification/useDeviceToken.js @@ -0,0 +1,30 @@ +import { useState } from "react"; +import { initializeApp } from "firebase/app"; +import { getToken, getMessaging } from "firebase/messaging"; +import { firebaseConfig } from "../../../app/config"; +const messaging = getMessaging(initializeApp(firebaseConfig)); +const useDeviceToken = (vapidKey) => { + const [token, setToken] = useState(null); + + getToken(messaging, { + vapidKey, + }) + .then((currentToken) => { + if (currentToken) { + console.log("current token for client: ", currentToken); + setToken(currentToken); + // updateDeviceToken(currentToken) + // Perform any other neccessary action with the token + } else { + // Show permission request UI + console.log( + "No registration token available. Request permission to generate one." + ); + } + }) + .catch((err) => { + console.log("An error occurred while retrieving token. ", err); + }); + return token; +}; +export default useDeviceToken; diff --git a/src/service-worker.tmp.js b/src/service-worker.tmp.js new file mode 100644 index 00000000..a13cec68 --- /dev/null +++ b/src/service-worker.tmp.js @@ -0,0 +1,61 @@ +// This a service worker file for receiving push notifitications. +// See `Access registration token section` @ https://firebase.google.com/docs/cloud-messaging/js/client#retrieve-the-current-registration-token +import { firebaseConfig } from "./app/config"; +import { initializeApp } from "firebase/app"; +import { getMessaging } from "firebase/messaging"; +// Initialize the Firebase app in the service worker by passing the generated config +// Retrieve firebase messaging +const messaging = getMessaging(initializeApp(firebaseConfig)); +console.log("wwwwwwwwww"); +// Handle incoming messages while the app is not in focus (i.e in the background, hidden behind other tabs, or completely closed). +// data:{from_server_id} +messaging.onBackgroundMessage((payload) => { + console.log("Received background message ", payload); + + const notificationTitle = payload.notification.title; + const notificationOptions = { + data: payload.data, + body: payload.notification.body, + }; + + self.registration.showNotification(notificationTitle, notificationOptions); +}); + +self.addEventListener("notificationclick", function (event) { + console.log("notification click", event, event.notification); + event.waitUntil( + (async function () { + const allClients = await clients.matchAll({ + includeUncontrolled: true, + }); + const [firstClient] = allClients; + // 没有数据 + if (!event.notification.data) { + firstClient.focus(); + return; + } + const { + rustchat_from_uid, + rustchat_to_uid, + rustchat_to_gid, + } = event.notification.data; + + // let chatClient; + let redirectPath = rustchat_to_uid + ? `/chat/dm/${rustchat_from_uid}` + : rustchat_to_gid + ? `/chat/channel/${rustchat_to_gid}` + : ""; + if (!redirectPath) { + firstClient.focus(); + return; + } + if (allClients.length !== 0) { + firstClient.postMessage({ newPath: redirectPath }); + firstClient.focus(); + } + })() + ); +}); + +// self.addEventListener("notificationclose", function (event) {});