logo

pleroma-fe

My custom branche(s) on git.pleroma.social/pleroma/pleroma-fe git clone https://hacktivis.me/git/pleroma-fe.git

push.js (3722B)


  1. import runtime from 'serviceworker-webpack5-plugin/lib/runtime'
  2. function urlBase64ToUint8Array (base64String) {
  3. const padding = '='.repeat((4 - base64String.length % 4) % 4)
  4. const base64 = (base64String + padding)
  5. .replace(/-/g, '+')
  6. .replace(/_/g, '/')
  7. const rawData = window.atob(base64)
  8. return Uint8Array.from([...rawData].map((char) => char.charCodeAt(0)))
  9. }
  10. function isPushSupported () {
  11. return 'serviceWorker' in navigator && 'PushManager' in window
  12. }
  13. function getOrCreateServiceWorker () {
  14. return runtime.register()
  15. .catch((err) => console.error('Unable to get or create a service worker.', err))
  16. }
  17. function subscribePush (registration, isEnabled, vapidPublicKey) {
  18. if (!isEnabled) return Promise.reject(new Error('Web Push is disabled in config'))
  19. if (!vapidPublicKey) return Promise.reject(new Error('VAPID public key is not found'))
  20. const subscribeOptions = {
  21. userVisibleOnly: true,
  22. applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)
  23. }
  24. return registration.pushManager.subscribe(subscribeOptions)
  25. }
  26. function unsubscribePush (registration) {
  27. return registration.pushManager.getSubscription()
  28. .then((subscribtion) => {
  29. if (subscribtion === null) { return }
  30. return subscribtion.unsubscribe()
  31. })
  32. }
  33. function deleteSubscriptionFromBackEnd (token) {
  34. return window.fetch('/api/v1/push/subscription/', {
  35. method: 'DELETE',
  36. headers: {
  37. 'Content-Type': 'application/json',
  38. Authorization: `Bearer ${token}`
  39. }
  40. }).then((response) => {
  41. if (!response.ok) throw new Error('Bad status code from server.')
  42. return response
  43. })
  44. }
  45. function sendSubscriptionToBackEnd (subscription, token, notificationVisibility) {
  46. return window.fetch('/api/v1/push/subscription/', {
  47. method: 'POST',
  48. headers: {
  49. 'Content-Type': 'application/json',
  50. Authorization: `Bearer ${token}`
  51. },
  52. body: JSON.stringify({
  53. subscription,
  54. data: {
  55. alerts: {
  56. follow: notificationVisibility.follows,
  57. favourite: notificationVisibility.likes,
  58. mention: notificationVisibility.mentions,
  59. reblog: notificationVisibility.repeats,
  60. move: notificationVisibility.moves
  61. }
  62. }
  63. })
  64. }).then((response) => {
  65. if (!response.ok) throw new Error('Bad status code from server.')
  66. return response.json()
  67. }).then((responseData) => {
  68. if (!responseData.id) throw new Error('Bad response from server.')
  69. return responseData
  70. })
  71. }
  72. export function registerPushNotifications (isEnabled, vapidPublicKey, token, notificationVisibility) {
  73. if (isPushSupported()) {
  74. getOrCreateServiceWorker()
  75. .then((registration) => subscribePush(registration, isEnabled, vapidPublicKey))
  76. .then((subscription) => sendSubscriptionToBackEnd(subscription, token, notificationVisibility))
  77. .catch((e) => console.warn(`Failed to setup Web Push Notifications: ${e.message}`))
  78. }
  79. }
  80. export function unregisterPushNotifications (token) {
  81. if (isPushSupported()) {
  82. Promise.all([
  83. deleteSubscriptionFromBackEnd(token),
  84. getOrCreateServiceWorker()
  85. .then((registration) => {
  86. return unsubscribePush(registration).then((result) => [registration, result])
  87. })
  88. .then(([registration, unsubResult]) => {
  89. if (!unsubResult) {
  90. console.warn('Push subscription cancellation wasn\'t successful, killing SW anyway...')
  91. }
  92. return registration.unregister().then((result) => {
  93. if (!result) {
  94. console.warn('Failed to kill SW')
  95. }
  96. })
  97. })
  98. ]).catch((e) => console.warn(`Failed to disable Web Push Notifications: ${e.message}`))
  99. }
  100. }