read message_delivery_method_web_push_vapid_public_key from public settings db
Main daploy / deploy (push) Successful in 43s
Main daploy / deploy (push) Successful in 43s
This commit is contained in:
@@ -5,6 +5,7 @@ import type {
|
||||
MessageDocument,
|
||||
WebPushSubscriptionDocument,
|
||||
} from '@/types/DBDocumentTypes'
|
||||
import type { PublicSettingsDocument } from '@/types/DBDocumentTypes/PublicSettingsDocument'
|
||||
|
||||
export const qrCodeDbRemote = new PouchDB<QRCodeDocument>(`${import.meta.env.VITE_API_URL}/qr`, {
|
||||
skip_setup: true,
|
||||
@@ -21,6 +22,13 @@ export const webPushSubscriptionsDbRemote = new PouchDB<WebPushSubscriptionDocum
|
||||
},
|
||||
)
|
||||
|
||||
export const publicSettingsDbRemote = new PouchDB<PublicSettingsDocument>(
|
||||
`${import.meta.env.VITE_API_URL}/public_settings`,
|
||||
{
|
||||
skip_setup: true,
|
||||
},
|
||||
)
|
||||
|
||||
export const messagesDbRemote = new PouchDB<MessageDocument>(
|
||||
`${import.meta.env.VITE_API_URL}/messages`,
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { WebPushSubscriptionDocument } from '@/types/DBDocumentTypes'
|
||||
import { webPushSubscriptionsDbRemote } from '@/api/dbs'
|
||||
import { publicSettingsDbRemote, webPushSubscriptionsDbRemote } from '@/api/dbs'
|
||||
import { getUserUuid } from '@/utils/getUserUuid'
|
||||
import { getBrowserUuid } from '@/utils/getBrowserUuid'
|
||||
|
||||
@@ -39,3 +39,10 @@ export const saveWebPushSubscription = async (subscription: PushSubscription) =>
|
||||
console.error('Ошибка сохранения подписки:', error)
|
||||
}
|
||||
}
|
||||
|
||||
export const getVapidPublicKey = async () => {
|
||||
const { value } = await publicSettingsDbRemote.get(
|
||||
'public_settings:message_delivery_method_web_push_vapid_public_key',
|
||||
)
|
||||
return value
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<template>
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-spin pi-spinner" v-if="isLoading"></i>
|
||||
|
||||
<RadioButton
|
||||
v-else
|
||||
v-model="model"
|
||||
:inputId="method"
|
||||
name="delivery"
|
||||
@@ -15,7 +18,11 @@
|
||||
import type { QRCodeDocument } from '@/types/DBDocumentTypes'
|
||||
import type { DeliveryOption } from '@/constants/deliveryOptions'
|
||||
|
||||
defineProps<{ label: DeliveryOption['label']; method: DeliveryOption['method'] }>()
|
||||
defineProps<{
|
||||
label: DeliveryOption['label']
|
||||
method: DeliveryOption['method']
|
||||
isLoading?: boolean
|
||||
}>()
|
||||
defineEmits<{
|
||||
(e: 'change', value: Event): void
|
||||
}>()
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
<template>
|
||||
<CreateMessageDeliveryOption :label :method v-model="model" @change="handleSelection()" />
|
||||
<CreateMessageDeliveryOption :isLoading="isLoading" :label :method v-model="model" />
|
||||
|
||||
<!-- Ошибка разрешений -->
|
||||
<p v-if="permissionError && model === method" class="text-red-500 mb-2">
|
||||
Не удалось получить разрешение на отправку уведомлений.<br />
|
||||
<button @click="retryPushSubscription" class="text-blue-500 underline">Повторить</button>
|
||||
<p v-if="isError && model === method" class="text-red-500 mb-2">
|
||||
{{ error }}.<br />
|
||||
<button @click="retry()" class="text-blue-500 underline">Повторить</button>
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { type QRCodeDocument } from '@/types/DBDocumentTypes'
|
||||
import { type DeliveryOption, DELIVERY_METHOD_WEB_PUSH } from '@/constants/deliveryOptions'
|
||||
import { ref } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
|
||||
import { saveWebPushSubscription } from '@/api/webPush'
|
||||
import { getVapidPublicKey, saveWebPushSubscription } from '@/api/webPush'
|
||||
|
||||
type DeliveryOptionWebPush = Extract<DeliveryOption, { method: typeof DELIVERY_METHOD_WEB_PUSH }>
|
||||
|
||||
@@ -28,52 +29,44 @@ const emit = defineEmits<{
|
||||
|
||||
const model = defineModel<null | QRCodeDocument['messageDeliveryMethod']>()
|
||||
|
||||
// Локальное состояние для уведомлений и ошибок
|
||||
const permissionError = ref(false)
|
||||
|
||||
// Обработчик выбора
|
||||
async function handleSelection() {
|
||||
permissionError.value = false
|
||||
const permission = await requestNotificationPermission()
|
||||
if (permission) {
|
||||
emit('change')
|
||||
} else {
|
||||
permissionError.value = true
|
||||
}
|
||||
}
|
||||
|
||||
// Функция запроса разрешений и подписки
|
||||
async function requestNotificationPermission(): Promise<boolean> {
|
||||
async function requestNotificationPermission() {
|
||||
if (!('Notification' in window)) {
|
||||
console.error('Уведомления не поддерживаются этим браузером.')
|
||||
return false
|
||||
throw new Error('Уведомления не поддерживаются этим браузером.')
|
||||
}
|
||||
|
||||
try {
|
||||
const applicationServerKeyPromise = getVapidPublicKey()
|
||||
|
||||
const permission = await Notification.requestPermission()
|
||||
if (permission !== 'granted') {
|
||||
console.error('Разрешение на уведомления не предоставлено.')
|
||||
return false
|
||||
throw new Error('Разрешение на уведомления не предоставлено.')
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker.ready
|
||||
const subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey:
|
||||
'BMPwpR1Q24ZOFxy2T9M-I-Y6F6bucsHFVZKP8QYslgD_4hGCDv16qnZnji-ldngcZ_vBWVBwJ6OIfknVBnCxLsY',
|
||||
applicationServerKey: await applicationServerKeyPromise,
|
||||
})
|
||||
|
||||
await saveWebPushSubscription(subscription)
|
||||
return true
|
||||
const webPushSubscriptionDoc = await saveWebPushSubscription(subscription)
|
||||
emit('change')
|
||||
|
||||
return webPushSubscriptionDoc
|
||||
} catch (err) {
|
||||
console.error('Ошибка при создании Push-подписки:', err)
|
||||
return false
|
||||
throw new Error('Ошибка при создании Push-подписки: ' + (err as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
// Повторный запрос разрешений
|
||||
function retryPushSubscription() {
|
||||
permissionError.value = false
|
||||
handleSelection()
|
||||
}
|
||||
const {
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
refetch: retry,
|
||||
} = useQuery({
|
||||
enabled: computed(() => model.value === DELIVERY_METHOD_WEB_PUSH),
|
||||
queryKey: ['createPushSubscription'],
|
||||
queryFn: () => requestNotificationPermission(),
|
||||
retry: false,
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { BaseDocument } from '@/types/DBDocumentTypes/BaseDocument'
|
||||
|
||||
export interface PublicSettingsDocument extends BaseDocument {
|
||||
_id: string // Формат: "public_settings:<name>"
|
||||
type: 'public_settings'
|
||||
|
||||
/**
|
||||
* Название настройки
|
||||
*/
|
||||
name: string
|
||||
|
||||
/**
|
||||
* Значение настройки
|
||||
*/
|
||||
value: string
|
||||
}
|
||||
@@ -11,12 +11,17 @@ const dbsSecurity = {
|
||||
},
|
||||
server_settings: {
|
||||
admins: { roles: ["_admin"] },
|
||||
qr: {
|
||||
admins: { roles: ["_admin"] },
|
||||
members: { roles: [] },
|
||||
|
||||
members: { roles: ["_admin"] },
|
||||
},
|
||||
// qr: {
|
||||
// admins: { roles: ["_admin"] },
|
||||
// members: { roles: [] },
|
||||
// },
|
||||
public_settings: {
|
||||
admins: { roles: ["_admin"] },
|
||||
members: { roles: [] },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const up = async () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import webpush from "web-push";
|
||||
import PouchDB from "./PouchDB.js";
|
||||
|
||||
if (!process.env.VAPID_SUBJECT) {
|
||||
throw new Error('VAPID_SUBJECT env is empty!');
|
||||
throw new Error("VAPID_SUBJECT env is empty!");
|
||||
}
|
||||
|
||||
const vapidKeys = webpush.generateVAPIDKeys();
|
||||
@@ -16,3 +16,12 @@ await new PouchDB(`${process.env.API_URL}/server_settings`, {
|
||||
keys: vapidKeys,
|
||||
},
|
||||
});
|
||||
|
||||
await new PouchDB(`${process.env.API_URL}/public_settings`, {
|
||||
skip_setup: true,
|
||||
}).put({
|
||||
_id: "public_settings:message_delivery_method_web_push_vapid_public_key",
|
||||
type: "public_settings",
|
||||
name: "message_delivery_method_web_push_vapid_public_key",
|
||||
value: vapidKeys.publicKey,
|
||||
});
|
||||
|
||||
@@ -24,8 +24,9 @@
|
||||
},
|
||||
"contributors": [],
|
||||
"scripts": {
|
||||
"dev": "",
|
||||
"test": ""
|
||||
"generate-keys": "node ./generate-keys.js",
|
||||
"test-send-notification": "node ./test-send-notification.js",
|
||||
"test-send-notification-cancel": "node ./test-send-notification-cancel.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"pouchdb-adapter-http": "^9.0.0",
|
||||
|
||||
@@ -22,13 +22,30 @@ const notification = {
|
||||
options: {
|
||||
icon: "/images/qr-code-logo-200x200.jpg",
|
||||
body: "Test push message from DevTools.",
|
||||
tag: "2105ef6f-3ca6-4f99-b258-0ca23f014309",
|
||||
tag: "01936062-d10f-7f2f-8ae3-dd7f9fbc5c7f",
|
||||
vibrate: [200, 100, 200, 100, 200, 100, 200],
|
||||
data: {
|
||||
url: "http://localhost:5173/chat/6ilhxu/13trvu",
|
||||
payload: { tag: "01936062-d10f-7f2f-8ae3-dd7f9fbc5c7f" },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const notification2 = {
|
||||
type: "notification",
|
||||
notification: {
|
||||
title: "test",
|
||||
options: {
|
||||
icon: "/images/qr-code-logo-200x200.jpg",
|
||||
body: "Test push message from DevTools.",
|
||||
tag: "01936062-d10f-7f2f-8ae3-dd7f9fbc5c7f",
|
||||
// requireInteraction: true,
|
||||
// silent: false,
|
||||
// vibrate: [200, 100, 200, 100, 200, 100, 200],
|
||||
data: {
|
||||
url: "/chat/6ilhxu/13trvu",
|
||||
payload: { tag: "2105ef6f-3ca6-4f99-b258-0ca23f014309" },
|
||||
payload: { tag: "01936062-d10f-7f2f-8ae3-dd7f9fbc5c7f" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -50,7 +67,7 @@ const { rows } = await new PouchDB(
|
||||
},
|
||||
);
|
||||
|
||||
await Promise.allSettled(
|
||||
const result = await Promise.allSettled(
|
||||
rows.map(async ({ doc }) => {
|
||||
await webpush.sendNotification(
|
||||
doc.subscription,
|
||||
@@ -59,6 +76,7 @@ await Promise.allSettled(
|
||||
console.log("sent ", doc._id);
|
||||
}),
|
||||
);
|
||||
console.log(result);
|
||||
|
||||
// issues:
|
||||
// 1. NO SOUND
|
||||
|
||||
Reference in New Issue
Block a user