feat: browser push notifications (#14888)
* feat: web push notifications feature * Revert yarn.lock changes * added new env variables requirement in .env.example * moved useNotifications hook in packages/lib/hooks * fix: bug * use i18n * chore: move to new file * chore: add yarn.lock * Update .env.example Co-authored-by: Amit Sharma <[email protected]> * chore: add instruction for brave browser * fix: tooltip * chore: use enum * chore * small update --------- Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Udit Takkar <[email protected]> Co-authored-by: Udit Takkar <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Amit Sharma <[email protected]> Co-authored-by: Carina Wollendorfer <[email protected]> Co-authored-by: unknown <[email protected]> Co-authored-by: Anik Dhabal Babu <[email protected]>
This commit is contained in:
17 files changed
+465
-11
No files matched your search
@@ -0,0 +1,40 @@
|
||||
import webpush from "web-push";
|
||||
|
||||
const vapidKeys = {
|
||||
publicKey: process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY || "",
|
||||
privateKey: process.env.VAPID_PRIVATE_KEY || "",
|
||||
};
|
||||
|
||||
// The mail to email address should be the one at which push service providers can reach you. It can also be a URL.
|
||||
webpush.setVapidDetails("https://cal.com", vapidKeys.publicKey, vapidKeys.privateKey);
|
||||
|
||||
type Subscription = {
|
||||
endpoint: string;
|
||||
keys: {
|
||||
auth: string;
|
||||
p256dh: string;
|
||||
};
|
||||
};
|
||||
|
||||
export const sendNotification = async ({
|
||||
subscription,
|
||||
title,
|
||||
body,
|
||||
icon,
|
||||
}: {
|
||||
subscription: Subscription;
|
||||
title: string;
|
||||
body: string;
|
||||
icon?: string;
|
||||
}) => {
|
||||
try {
|
||||
const payload = JSON.stringify({
|
||||
title,
|
||||
body,
|
||||
icon,
|
||||
});
|
||||
await webpush.sendNotification(subscription, payload);
|
||||
} catch (error) {
|
||||
console.error("Error sending notification", error);
|
||||
}
|
||||
};
|
||||
@@ -18,9 +18,11 @@
|
||||
"react-select": "^5.7.0",
|
||||
"react-sticky-box": "^2.0.4",
|
||||
"react-virtual": "^2.10.4",
|
||||
"web-push": "^3.6.7",
|
||||
"zustand": "^4.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/react-hooks": "^8.0.1"
|
||||
"@testing-library/react-hooks": "^8.0.1",
|
||||
"@types/web-push": "^3.6.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui";
|
||||
|
||||
export enum ButtonState {
|
||||
NONE = "none",
|
||||
ALLOW = "allow",
|
||||
DISABLE = "disable",
|
||||
DENIED = "denied",
|
||||
}
|
||||
|
||||
export const useNotifications = () => {
|
||||
const [buttonToShow, setButtonToShow] = useState<ButtonState>(ButtonState.NONE);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { t } = useLocale();
|
||||
|
||||
const { mutate: addSubscription } = trpc.viewer.addNotificationsSubscription.useMutation({
|
||||
onSuccess: () => {
|
||||
setButtonToShow(ButtonState.DISABLE);
|
||||
showToast(t("browser_notifications_turned_on"), "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(`Error: ${error.message}`, "error");
|
||||
},
|
||||
onSettled: () => {
|
||||
setIsLoading(false);
|
||||
},
|
||||
});
|
||||
const { mutate: removeSubscription } = trpc.viewer.removeNotificationsSubscription.useMutation({
|
||||
onSuccess: () => {
|
||||
setButtonToShow(ButtonState.ALLOW);
|
||||
showToast(t("browser_notifications_turned_off"), "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(`Error: ${error.message}`, "error");
|
||||
},
|
||||
onSettled: () => {
|
||||
setIsLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const decideButtonToShow = async () => {
|
||||
if (!("Notification" in window)) {
|
||||
console.log("Notifications not supported");
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker?.getRegistration();
|
||||
if (!registration) return;
|
||||
const subscription = await registration.pushManager.getSubscription();
|
||||
|
||||
const permission = Notification.permission;
|
||||
|
||||
if (permission === ButtonState.DENIED) {
|
||||
setButtonToShow(ButtonState.DENIED);
|
||||
return;
|
||||
}
|
||||
|
||||
if (permission === "default") {
|
||||
setButtonToShow(ButtonState.ALLOW);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!subscription) {
|
||||
setButtonToShow(ButtonState.ALLOW);
|
||||
return;
|
||||
}
|
||||
|
||||
setButtonToShow(ButtonState.DISABLE);
|
||||
};
|
||||
|
||||
decideButtonToShow();
|
||||
}, []);
|
||||
|
||||
const enableNotifications = async () => {
|
||||
setIsLoading(true);
|
||||
const permissionResponse = await Notification.requestPermission();
|
||||
|
||||
if (permissionResponse === ButtonState.DENIED) {
|
||||
setButtonToShow(ButtonState.DENIED);
|
||||
setIsLoading(false);
|
||||
showToast(t("browser_notifications_denied"), "warning");
|
||||
return;
|
||||
}
|
||||
|
||||
if (permissionResponse === "default") {
|
||||
setIsLoading(false);
|
||||
showToast(t("please_allow_notifications"), "warning");
|
||||
return;
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker?.getRegistration();
|
||||
if (!registration) {
|
||||
// This will not happen ideally as the button will not be shown if the service worker is not registered
|
||||
return;
|
||||
}
|
||||
|
||||
let subscription: PushSubscription;
|
||||
try {
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlB64ToUint8Array(process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY || ""),
|
||||
});
|
||||
} catch (error) {
|
||||
// This happens in Brave browser as it does not have a push service
|
||||
console.error(error);
|
||||
setIsLoading(false);
|
||||
setButtonToShow(ButtonState.NONE);
|
||||
showToast(t("browser_notifications_not_supported"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
addSubscription(
|
||||
{ subscription: JSON.stringify(subscription) },
|
||||
{
|
||||
onError: async () => {
|
||||
await subscription.unsubscribe();
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const disableNotifications = async () => {
|
||||
setIsLoading(true);
|
||||
const registration = await navigator.serviceWorker?.getRegistration();
|
||||
if (!registration) {
|
||||
// This will not happen ideally as the button will not be shown if the service worker is not registered
|
||||
return;
|
||||
}
|
||||
const subscription = await registration.pushManager.getSubscription();
|
||||
if (!subscription) {
|
||||
// This will not happen ideally as the button will not be shown if the subscription is not present
|
||||
return;
|
||||
}
|
||||
removeSubscription(
|
||||
{ subscription: JSON.stringify(subscription) },
|
||||
{
|
||||
onSuccess: async () => {
|
||||
await subscription.unsubscribe();
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
buttonToShow,
|
||||
isLoading,
|
||||
enableNotifications,
|
||||
disableNotifications,
|
||||
};
|
||||
};
|
||||
|
||||
const urlB64ToUint8Array = (base64String: string) => {
|
||||
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;
|
||||
};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "NotificationsSubscriptions" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"userId" INTEGER NOT NULL,
|
||||
"subscription" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "NotificationsSubscriptions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "NotificationsSubscriptions_userId_subscription_idx" ON "NotificationsSubscriptions"("userId", "subscription");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "NotificationsSubscriptions" ADD CONSTRAINT "NotificationsSubscriptions_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -331,9 +331,10 @@ model User {
|
||||
secondaryEmails SecondaryEmail[]
|
||||
isPlatformManaged Boolean @default(false)
|
||||
|
||||
OutOfOfficeReasons OutOfOfficeReason[]
|
||||
smsLockState SMSLockState @default(UNLOCKED)
|
||||
smsLockReviewedByAdmin Boolean @default(false)
|
||||
OutOfOfficeReasons OutOfOfficeReason[]
|
||||
smsLockState SMSLockState @default(UNLOCKED)
|
||||
smsLockReviewedByAdmin Boolean @default(false)
|
||||
NotificationsSubscriptions NotificationsSubscriptions[]
|
||||
|
||||
@@unique([email])
|
||||
@@unique([email, username])
|
||||
@@ -346,6 +347,15 @@ model User {
|
||||
@@map(name: "users")
|
||||
}
|
||||
|
||||
model NotificationsSubscriptions {
|
||||
id Int @id @default(autoincrement())
|
||||
userId Int
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
subscription String
|
||||
|
||||
@@index([userId, subscription])
|
||||
}
|
||||
|
||||
// It holds Organization Profiles as well as User Profiles for users that have been added to an organization
|
||||
model Profile {
|
||||
id Int @id @default(autoincrement())
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import authedProcedure from "../../procedures/authedProcedure";
|
||||
import { importHandler, router } from "../../trpc";
|
||||
import { ZAddNotificationsSubscriptionInputSchema } from "./addNotificationsSubscription.schema";
|
||||
import { ZAddSecondaryEmailInputSchema } from "./addSecondaryEmail.schema";
|
||||
import { ZAppByIdInputSchema } from "./appById.schema";
|
||||
import { ZAppCredentialsByTypeInputSchema } from "./appCredentialsByType.schema";
|
||||
@@ -16,6 +17,7 @@ import { ZNoShowInputSchema } from "./markNoShow.schema";
|
||||
import { ZOutOfOfficeInputSchema, ZOutOfOfficeDelete } from "./outOfOffice.schema";
|
||||
import { me } from "./procedures/me";
|
||||
import { teamsAndUserProfilesQuery } from "./procedures/teamsAndUserProfilesQuery";
|
||||
import { ZRemoveNotificationsSubscriptionInputSchema } from "./removeNotificationsSubscription.schema";
|
||||
import { ZRoutingFormOrderInputSchema } from "./routingFormOrder.schema";
|
||||
import { ZSetDestinationCalendarInputSchema } from "./setDestinationCalendar.schema";
|
||||
import { ZSubmitFeedbackInputSchema } from "./submitFeedback.schema";
|
||||
@@ -59,6 +61,8 @@ type AppsRouterHandlerCache = {
|
||||
addSecondaryEmail?: typeof import("./addSecondaryEmail.handler").addSecondaryEmailHandler;
|
||||
getTravelSchedules?: typeof import("./getTravelSchedules.handler").getTravelSchedulesHandler;
|
||||
outOfOfficeReasonList?: typeof import("./outOfOfficeReasons.handler").outOfOfficeReasonList;
|
||||
addNotificationsSubscription?: typeof import("./addNotificationsSubscription.handler").addNotificationsSubscriptionHandler;
|
||||
removeNotificationsSubscription?: typeof import("./removeNotificationsSubscription.handler").removeNotificationsSubscriptionHandler;
|
||||
markNoShow?: typeof import("./markNoShow.handler").markNoShow;
|
||||
};
|
||||
|
||||
@@ -503,6 +507,38 @@ export const loggedInViewerRouter = router({
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.outOfOfficeReasonList();
|
||||
}),
|
||||
addNotificationsSubscription: authedProcedure
|
||||
.input(ZAddNotificationsSubscriptionInputSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.addNotificationsSubscription) {
|
||||
UNSTABLE_HANDLER_CACHE.addNotificationsSubscription = (
|
||||
await import("./addNotificationsSubscription.handler")
|
||||
).addNotificationsSubscriptionHandler;
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.addNotificationsSubscription) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.addNotificationsSubscription({ ctx, input });
|
||||
}),
|
||||
removeNotificationsSubscription: authedProcedure
|
||||
.input(ZRemoveNotificationsSubscriptionInputSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.removeNotificationsSubscription) {
|
||||
UNSTABLE_HANDLER_CACHE.removeNotificationsSubscription = (
|
||||
await import("./removeNotificationsSubscription.handler")
|
||||
).removeNotificationsSubscriptionHandler;
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.removeNotificationsSubscription) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.removeNotificationsSubscription({ ctx, input });
|
||||
}),
|
||||
markNoShow: authedProcedure.input(ZNoShowInputSchema).mutation(async (opts) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.markNoShow) {
|
||||
UNSTABLE_HANDLER_CACHE.markNoShow = (await import("./markNoShow.handler")).markNoShow;
|
||||
@@ -512,7 +548,6 @@ export const loggedInViewerRouter = router({
|
||||
if (!UNSTABLE_HANDLER_CACHE.markNoShow) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.markNoShow(opts);
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import type { TAddNotificationsSubscriptionInputSchema } from "./addNotificationsSubscription.schema";
|
||||
|
||||
type AddSecondaryEmailOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TAddNotificationsSubscriptionInputSchema;
|
||||
};
|
||||
|
||||
export const addNotificationsSubscriptionHandler = async ({ ctx, input }: AddSecondaryEmailOptions) => {
|
||||
const { user } = ctx;
|
||||
const { subscription } = input;
|
||||
|
||||
const existingSubscription = await prisma.notificationsSubscriptions.findFirst({
|
||||
where: { userId: user.id, subscription },
|
||||
});
|
||||
|
||||
if (!existingSubscription) {
|
||||
await prisma.notificationsSubscriptions.create({
|
||||
data: { userId: user.id, subscription },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
message: "Subscription added successfully",
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZAddNotificationsSubscriptionInputSchema = z.object({
|
||||
subscription: z.string(),
|
||||
});
|
||||
|
||||
export type TAddNotificationsSubscriptionInputSchema = z.infer<
|
||||
typeof ZAddNotificationsSubscriptionInputSchema
|
||||
>;
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import type { TRemoveNotificationsSubscriptionInputSchema } from "./removeNotificationsSubscription.schema";
|
||||
|
||||
type AddSecondaryEmailOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TRemoveNotificationsSubscriptionInputSchema;
|
||||
};
|
||||
|
||||
export const removeNotificationsSubscriptionHandler = async ({ ctx, input }: AddSecondaryEmailOptions) => {
|
||||
const { user } = ctx;
|
||||
const { subscription } = input;
|
||||
|
||||
// We just use findFirst because there will only be single unique subscription for a user
|
||||
const subscriptionToDelete = await prisma.notificationsSubscriptions.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
subscription,
|
||||
},
|
||||
});
|
||||
|
||||
if (subscriptionToDelete) {
|
||||
await prisma.notificationsSubscriptions.delete({
|
||||
where: {
|
||||
id: subscriptionToDelete.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
message: "Subscription removed successfully",
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZRemoveNotificationsSubscriptionInputSchema = z.object({
|
||||
subscription: z.string(),
|
||||
});
|
||||
|
||||
export type TRemoveNotificationsSubscriptionInputSchema = z.infer<
|
||||
typeof ZRemoveNotificationsSubscriptionInputSchema
|
||||
>;
|
||||
Reference in new issue
Block a user