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