-
Notifications
You must be signed in to change notification settings - Fork 901
feat(site): add webpush notification serviceworker #17123
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
58cc953
site changes from cj/push-notifications-2-rebase
johnstcn f729332
chore(coderd/webpush): add test helpers
johnstcn f047869
re-add context and sw after rebase
johnstcn 403c942
ignore empty events
johnstcn 58430ae
rename
johnstcn 0c4e54b
fix(webpush): set vapid sub in webpush payload
johnstcn 17b3f1c
whoops
johnstcn 5672188
remove debug msg
johnstcn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
re-add context and sw after rebase
- Loading branch information
commit f04786999e7072da746d47524ae4559e4c2427d0
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
import { API } from "api/api"; | ||
import { buildInfo } from "api/queries/buildInfo"; | ||
import { experiments } from "api/queries/experiments"; | ||
import { useEmbeddedMetadata } from "hooks/useEmbeddedMetadata"; | ||
import { useEffect, useState } from "react"; | ||
import { useQuery } from "react-query"; | ||
|
||
interface WebpushNotifications { | ||
readonly enabled: boolean; | ||
readonly subscribed: boolean; | ||
readonly loading: boolean; | ||
|
||
subscribe(): Promise<void>; | ||
unsubscribe(): Promise<void>; | ||
} | ||
|
||
export const useWebpushNotifications = (): WebpushNotifications => { | ||
const { metadata } = useEmbeddedMetadata(); | ||
const buildInfoQuery = useQuery(buildInfo(metadata["build-info"])); | ||
const enabledExperimentsQuery = useQuery(experiments(metadata.experiments)); | ||
|
||
const [subscribed, setSubscribed] = useState<boolean>(false); | ||
const [loading, setLoading] = useState<boolean>(true); | ||
const [enabled, setEnabled] = useState<boolean>(false); | ||
|
||
useEffect(() => { | ||
// Check if the experiment is enabled. | ||
if (enabledExperimentsQuery.data?.includes("web-push")) { | ||
setEnabled(true); | ||
} | ||
|
||
// Check if browser supports push notifications | ||
if (!("Notification" in window) || !("serviceWorker" in navigator)) { | ||
setSubscribed(false); | ||
setLoading(false); | ||
return; | ||
} | ||
|
||
const checkSubscription = async () => { | ||
try { | ||
const registration = await navigator.serviceWorker.ready; | ||
const subscription = await registration.pushManager.getSubscription(); | ||
setSubscribed(!!subscription); | ||
} catch (error) { | ||
console.error("Error checking push subscription:", error); | ||
setSubscribed(false); | ||
} finally { | ||
setLoading(false); | ||
} | ||
}; | ||
|
||
checkSubscription(); | ||
}, [enabledExperimentsQuery.data]); | ||
|
||
const subscribe = async (): Promise<void> => { | ||
try { | ||
setLoading(true); | ||
const registration = await navigator.serviceWorker.ready; | ||
const vapidPublicKey = buildInfoQuery.data?.webpush_public_key; | ||
|
||
const subscription = await registration.pushManager.subscribe({ | ||
userVisibleOnly: true, | ||
applicationServerKey: vapidPublicKey, | ||
}); | ||
const json = subscription.toJSON(); | ||
if (!json.keys || !json.endpoint) { | ||
throw new Error("No keys or endpoint found"); | ||
} | ||
|
||
await API.createNotificationPushSubscription("me", { | ||
endpoint: json.endpoint, | ||
auth_key: json.keys.auth, | ||
p256dh_key: json.keys.p256dh, | ||
}); | ||
|
||
setSubscribed(true); | ||
} catch (error) { | ||
console.error("Subscription failed:", error); | ||
throw error; | ||
} finally { | ||
setLoading(false); | ||
} | ||
}; | ||
|
||
const unsubscribe = async (): Promise<void> => { | ||
try { | ||
setLoading(true); | ||
const registration = await navigator.serviceWorker.ready; | ||
const subscription = await registration.pushManager.getSubscription(); | ||
|
||
if (subscription) { | ||
await subscription.unsubscribe(); | ||
setSubscribed(false); | ||
} | ||
} catch (error) { | ||
console.error("Unsubscription failed:", error); | ||
throw error; | ||
} finally { | ||
setLoading(false); | ||
} | ||
}; | ||
|
||
return { | ||
subscribed, | ||
enabled, | ||
loading: loading || buildInfoQuery.isLoading, | ||
subscribe, | ||
unsubscribe, | ||
}; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
/// <reference lib="webworker" /> | ||
|
||
import type { WebpushMessage } from "api/typesGenerated"; | ||
|
||
// @ts-ignore | ||
declare const self: ServiceWorkerGlobalScope; | ||
|
||
self.addEventListener("install", (event) => { | ||
self.skipWaiting(); | ||
}); | ||
|
||
self.addEventListener("activate", (event) => { | ||
event.waitUntil(self.clients.claim()); | ||
}); | ||
|
||
self.addEventListener("push", (event) => { | ||
let payload: WebpushMessage; | ||
try { | ||
payload = event.data?.json(); | ||
} catch (e) { | ||
console.error("Error parsing push payload:", e); | ||
return; | ||
} | ||
|
||
event.waitUntil( | ||
self.registration.showNotification(payload.title, { | ||
body: payload.body || "", | ||
icon: payload.icon || "/favicon.ico", | ||
}), | ||
); | ||
}); | ||
|
||
// Handle notification click | ||
self.addEventListener("notificationclick", (event) => { | ||
event.notification.close(); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.