WIP FCM push messaging.
This commit is contained in:
12
bodyshop-dev-firebase-adminsdk.json
Normal file
12
bodyshop-dev-firebase-adminsdk.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"type": "service_account",
|
||||
"project_id": "bodyshop-dev-b1cb6",
|
||||
"private_key_id": "68cbb23486745271eb9ebd19b544f4f0ffff208f",
|
||||
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCkw6wLHLibOjc2\npCoHqZ2pc1AbrecocNWVnVF8W7j8Zkc/oacwNVD/EMZ7dDjlT9vcmf71Yw2mDWOO\njQaXSlOASkDYE0jDYyMyYflonaGyGmAemyirRqXV78g9hliAMcS+HL6wL7HpZ8Y3\nGVp9pYn792aJnCrXJOZvRFqx+eOBztLADBmBpMH4u9FFM6ZdLuWjmgKJwx5u/jYx\nFIxJuEA1Zo1ZPT9D5amgYzmI4Tjvj8b5WzlsFA7HEkAV96f3AY4cnIWqlz6Vm2qR\nXvroDueqzM6QbzqXI5iHKkcJfH1DQpjUyLX82+5nnTEoaYSqzy7ja2ILpBrY+Noh\nAWLsxq7bAgMBAAECggEAKlaPmIFmXJj+hB92H2bx+Q+FF7+9pRItiBcXT83gAJel\nmk/HPueMayab4jBQyHgXZp35uoOcB73sBb7uYST7xP0PoZZ+/Zo1eqZbaQsMeFA3\nv9WeAzkRtyI5AbpKdpKTXEjVpT90R6ZfdFwi+SN3DBScOCM1jPhR8GiPp6kvUXTy\n4DsYkcvTYBvzyKHqq4S1EhAaQT8ISznqEUywIS2ZyZiD7hY+kWgmQZVwIG8HlqXl\nXJZmMsBHD14f9h/vSxr9qp1Kwo/smh05DWzf7xXLOd/ZWb+N+VJPgdDJd/iEe6Xt\nm5GihwduIEsXoQu/8dEYc9mhwQnjpwmjO4B3AJTj1QKBgQDXGuN5/WuoMyUQzmEn\nrRS2oq4FsWD655s/cHWPMq9tW/7TxAEUxAyKNdP8kHvYSUg4XuKBGVIWbhsIlnwC\nG4ElHKktESRy2nQx8In+HQyDGhVbXjg2FqvvylF7eQJi4JLHroGA4zjmVsyHkd+F\nVozMG/VZwDEYppClVtP8HItltwKBgQDEFrbEbWB6N+n7O043Aab+R2Kw4sq/N9l0\nZ4ONFIPfTchp0cO4+vQp4vHHQoQRpRgTPnAia2Ra19WMVV50agLH/+nHWBwbaKw9\nK9XLmBiiqxMkRr70AphYSDeEyFHXvWUqmEr9ufO0B1ddGY/rIgxe+selu8ko7moG\nuizBZ94f/QKBgHQbiHP9jZHh4Xz72UdgTpDyqLpb73wfbhZFLr+X3UdLY/aMkwTR\nee9UdNOcbazmiXwcA2kp8Lw4vJDbIZ7Fl+UfXlX8Lc9tCVE3hFTM+0b82lBSQEc5\n3570dx0NyXLzw2bTVAXtIHZ8nbQD0kIX4LH/2WSTsCydI/CLOKuaAMhrAoGAUWFX\n4ve95ZtVCUZYtK2D395CkETffjKwlgXr695KyJ9ggMJk512HfebJDziE1UneTwZH\nxZEqaiVPZFl9xPTGSLjmDix8JcfwS8boiQGLn98+J30Q/PYiweje2cXFabMZzG6+\nGMVW5i1xzZqxRxWvaq/LsfXYi5s+96HGt1HjNwUCgYAkzxJFrSs6Jksw5Zj1G2AP\nTCNJv3jne9V66tNXpSjyTtFX0LDHcDKTafyS80Noz4SsxF9mAqTrueWfsOsDO8ul\nqdlM0Gj6K7V76Ldf59fYGzhaqq4RJADaWjxZ5DP97xTx5mMtVl5TBpAYFvxW9E9h\n4mMvZOe/P8k5MPlPoXrt1Q==\n-----END PRIVATE KEY-----\n",
|
||||
"client_email": "firebase-adminsdk-8mboc@bodyshop-dev-b1cb6.iam.gserviceaccount.com",
|
||||
"client_id": "106919386910689150709",
|
||||
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
||||
"token_uri": "https://oauth2.googleapis.com/token",
|
||||
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
||||
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-8mboc%40bodyshop-dev-b1cb6.iam.gserviceaccount.com"
|
||||
}
|
||||
44
client/public/firebase-messaging-sw.js
Normal file
44
client/public/firebase-messaging-sw.js
Normal file
@@ -0,0 +1,44 @@
|
||||
importScripts("https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js");
|
||||
importScripts(
|
||||
"https://www.gstatic.com/firebasejs/7.14.2/firebase-messaging.js"
|
||||
);
|
||||
|
||||
firebase.initializeApp({
|
||||
apiKey: "AIzaSyDV9MsSHZmpLtjoaTK_ObvjFaJ-nMSd2KA",
|
||||
authDomain: "bodyshop-dev-b1cb6.firebaseapp.com",
|
||||
databaseURL: "https://bodyshop-dev-b1cb6.firebaseio.com",
|
||||
projectId: "bodyshop-dev-b1cb6",
|
||||
storageBucket: "bodyshop-dev-b1cb6.appspot.com",
|
||||
messagingSenderId: "922785209028",
|
||||
appId: "1:922785209028:web:96e9df15401eee5d784791",
|
||||
measurementId: "G-2D5378VCHE",
|
||||
});
|
||||
|
||||
const messaging = firebase.messaging();
|
||||
|
||||
//Handles Background Messages
|
||||
messaging.setBackgroundMessageHandler(function (payload) {
|
||||
console.log("backgroundMessageHandler", payload);
|
||||
const promiseChain = clients
|
||||
.matchAll({
|
||||
type: "window",
|
||||
includeUncontrolled: true,
|
||||
})
|
||||
.then((windowClients) => {
|
||||
for (let i = 0; i < windowClients.length; i++) {
|
||||
const windowClient = windowClients[i];
|
||||
windowClient.postMessage(payload);
|
||||
}
|
||||
})
|
||||
.then(() => {
|
||||
return registration.showNotification(JSON.stringify(payload));
|
||||
});
|
||||
return promiseChain;
|
||||
});
|
||||
|
||||
//Handles the notification getting clicked.
|
||||
self.addEventListener("notificationclick", function (event) {
|
||||
// do what you want
|
||||
// ...
|
||||
console.log("SW notificationclick", event);
|
||||
});
|
||||
@@ -22,5 +22,6 @@
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#fff",
|
||||
"background_color": "#fff"
|
||||
"background_color": "#fff",
|
||||
"gcm_sender_id": "103953800507"
|
||||
}
|
||||
|
||||
@@ -11,10 +11,11 @@ import { WebSocketLink } from "apollo-link-ws";
|
||||
import { getMainDefinition } from "apollo-utilities";
|
||||
import React, { Component } from "react";
|
||||
import GlobalLoadingBar from "../components/global-loading-bar/global-loading-bar.component";
|
||||
import { auth } from "../firebase/firebase.utils";
|
||||
import { auth, messaging } from "../firebase/firebase.utils";
|
||||
import errorLink from "../graphql/apollo-error-handling";
|
||||
import App from "./App";
|
||||
import LogRocket from "logrocket";
|
||||
import { notification } from "antd";
|
||||
|
||||
if (process.env.NODE_ENV === "production") LogRocket.init("gvfvfw/bodyshopapp");
|
||||
|
||||
@@ -116,6 +117,22 @@ export default class AppContainer extends Component {
|
||||
this.state = { client };
|
||||
}
|
||||
|
||||
async componentDidMount() {
|
||||
messaging
|
||||
.requestPermission()
|
||||
.then(async function () {
|
||||
const token = await messaging.getToken();
|
||||
console.log("messaging -> token", token);
|
||||
})
|
||||
.catch(function (err) {
|
||||
console.log("Unable to get permission to notify.", err);
|
||||
});
|
||||
navigator.serviceWorker.addEventListener("message", (message) => {
|
||||
console.log("Comp Did Mount", message);
|
||||
notification["info"]({ message: JSON.stringify(message.data) });
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const { client } = this.state;
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import "firebase/firestore";
|
||||
import "firebase/auth";
|
||||
import "firebase/database";
|
||||
import "firebase/analytics";
|
||||
import "firebase/messaging";
|
||||
|
||||
const config = JSON.parse(process.env.REACT_APP_FIREBASE_CONFIG);
|
||||
firebase.initializeApp(config);
|
||||
@@ -32,3 +33,10 @@ export const updateCurrentUser = (userDetails) => {
|
||||
}, reject);
|
||||
});
|
||||
};
|
||||
|
||||
const messaging = firebase.messaging();
|
||||
messaging.usePublicVapidKey(
|
||||
// Project Settings => Cloud Messaging => Web Push certificates
|
||||
"BBlvtEL73vYinkiAgK5t51jgDTYj6961OO_5niP4Q5py_l5yhTL8IGYkpONyMGoXs8ZTdVhEWsu3_IEXcW0cIIg"
|
||||
);
|
||||
export { messaging };
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
// opt-in, read https://bit.ly/CRA-PWA
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
window.location.hostname === "localhost" ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
window.location.hostname === "[::1]" ||
|
||||
// 127.0.0.1/8 is considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
@@ -21,7 +21,7 @@ const isLocalhost = Boolean(
|
||||
);
|
||||
|
||||
export function register(config) {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
@@ -31,7 +31,7 @@ export function register(config) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
window.addEventListener("load", () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
|
||||
|
||||
if (isLocalhost) {
|
||||
@@ -42,8 +42,8 @@ export function register(config) {
|
||||
// service worker/PWA documentation.
|
||||
navigator.serviceWorker.ready.then(() => {
|
||||
console.log(
|
||||
'This web app is being served cache-first by a service ' +
|
||||
'worker. To learn more, visit https://bit.ly/CRA-PWA'
|
||||
"This web app is being served cache-first by a service " +
|
||||
"worker. To learn more, visit https://bit.ly/CRA-PWA"
|
||||
);
|
||||
});
|
||||
} else {
|
||||
@@ -52,26 +52,41 @@ export function register(config) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if ("serviceWorker" in navigator) {
|
||||
navigator.serviceWorker
|
||||
.register("./firebase-messaging-sw.js")
|
||||
.then(function (registration) {
|
||||
console.log("FCM Registration :", registration);
|
||||
console.log(
|
||||
"FCM Registration successful, scope is:",
|
||||
registration.scope
|
||||
);
|
||||
})
|
||||
.catch(function (err) {
|
||||
console.log("FCM Service worker registration failed, error:", err);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function registerValidSW(swUrl, config) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
.then((registration) => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing;
|
||||
if (installingWorker == null) {
|
||||
return;
|
||||
}
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (installingWorker.state === "installed") {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the updated precached content has been fetched,
|
||||
// but the previous service worker will still serve the older
|
||||
// content until all client tabs are closed.
|
||||
console.log(
|
||||
'New content is available and will be used when all ' +
|
||||
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
|
||||
"New content is available and will be used when all " +
|
||||
"tabs for this page are closed. See https://bit.ly/CRA-PWA."
|
||||
);
|
||||
|
||||
// Execute callback
|
||||
@@ -82,7 +97,7 @@ function registerValidSW(swUrl, config) {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
console.log('Content is cached for offline use.');
|
||||
console.log("Content is cached for offline use.");
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onSuccess) {
|
||||
@@ -93,23 +108,23 @@ function registerValidSW(swUrl, config) {
|
||||
};
|
||||
};
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error);
|
||||
.catch((error) => {
|
||||
console.error("Error during service worker registration:", error);
|
||||
});
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl, config) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl)
|
||||
.then(response => {
|
||||
.then((response) => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
const contentType = response.headers.get('content-type');
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (
|
||||
response.status === 404 ||
|
||||
(contentType != null && contentType.indexOf('javascript') === -1)
|
||||
(contentType != null && contentType.indexOf("javascript") === -1)
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
@@ -121,14 +136,14 @@ function checkValidServiceWorker(swUrl, config) {
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
"No internet connection found. App is running in offline mode."
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
if ("serviceWorker" in navigator) {
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
registration.unregister();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"dotenv": "8.2.0",
|
||||
"express": "^4.16.4",
|
||||
"express-sslify": "^1.2.0",
|
||||
"firebase-admin": "^8.11.0",
|
||||
"graphql-request": "^1.8.2",
|
||||
"handlebars": "^4.7.6",
|
||||
"nodemailer": "^6.4.4",
|
||||
|
||||
@@ -54,6 +54,9 @@ app.post(
|
||||
var renderHandlebars = require("./server/render/renderHandlebars");
|
||||
app.post("/render", renderHandlebars.render);
|
||||
|
||||
var fb = require("./server/firebase/firebase-handler");
|
||||
app.post("/notifications/send", fb.sendNotification);
|
||||
|
||||
//Serve React App if in Production
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
app.use(express.static(path.join(__dirname, "client/build")));
|
||||
|
||||
41
server/firebase/firebase-handler.js
Normal file
41
server/firebase/firebase-handler.js
Normal file
@@ -0,0 +1,41 @@
|
||||
var admin = require("firebase-admin");
|
||||
|
||||
var serviceAccount = require("../../bodyshop-dev-firebase-adminsdk.json");
|
||||
|
||||
admin.initializeApp({
|
||||
credential: admin.credential.cert(serviceAccount),
|
||||
databaseURL: "https://bodyshop-dev-b1cb6.firebaseio.com",
|
||||
});
|
||||
//var defaultApp = admin.initializeApp(defaultAppConfig);
|
||||
|
||||
exports.sendNotification = (req, res) => {
|
||||
console.log("Firebase Send.");
|
||||
// const { ids } = req.body;
|
||||
// const url = cloudinary.utils.download_zip_url({ public_ids: ids });
|
||||
|
||||
var registrationToken =
|
||||
"dwsrcoeaIpwEmSzrVkE-_V:APA91bFurr0yCN-yXcaNrJvn8_f47I4vb4avxeS0NR5SCBPNADFB-gC79Hdmj7wqPccPmZCx0NzA_Dqi1lLYegpN-tFvANaK9I00oOSsFnOxv6KNZDLW0WguwFA0vQN8X50BaGuLTQqM";
|
||||
|
||||
var message = {
|
||||
data: {
|
||||
title: "850",
|
||||
body: "2:45",
|
||||
},
|
||||
token: registrationToken,
|
||||
};
|
||||
|
||||
// Send a message to the device corresponding to the provided
|
||||
// registration token.
|
||||
admin
|
||||
.messaging()
|
||||
.send(message)
|
||||
.then((response) => {
|
||||
// Response is a message ID string.
|
||||
console.log("Successfully sent message:", response);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log("Error sending message:", error);
|
||||
});
|
||||
|
||||
res.sendStatus(200);
|
||||
};
|
||||
Reference in New Issue
Block a user