add guest subscribe push notification
This commit is contained in:
Vendored
+83
@@ -0,0 +1,83 @@
|
||||
/* eslint-disable */
|
||||
/* prettier-ignore */
|
||||
// @ts-nocheck
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
// Generated by unplugin-auto-import
|
||||
// biome-ignore lint: disable
|
||||
export {}
|
||||
declare global {
|
||||
const EffectScope: typeof import('vue')['EffectScope']
|
||||
const computed: typeof import('vue')['computed']
|
||||
const createApp: typeof import('vue')['createApp']
|
||||
const customRef: typeof import('vue')['customRef']
|
||||
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
|
||||
const defineComponent: typeof import('vue')['defineComponent']
|
||||
const effectScope: typeof import('vue')['effectScope']
|
||||
const getActiveHead: typeof import('unhead')['getActiveHead']
|
||||
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
|
||||
const getCurrentScope: typeof import('vue')['getCurrentScope']
|
||||
const h: typeof import('vue')['h']
|
||||
const inject: typeof import('vue')['inject']
|
||||
const isProxy: typeof import('vue')['isProxy']
|
||||
const isReactive: typeof import('vue')['isReactive']
|
||||
const isReadonly: typeof import('vue')['isReadonly']
|
||||
const isRef: typeof import('vue')['isRef']
|
||||
const markRaw: typeof import('vue')['markRaw']
|
||||
const nextTick: typeof import('vue')['nextTick']
|
||||
const onActivated: typeof import('vue')['onActivated']
|
||||
const onBeforeMount: typeof import('vue')['onBeforeMount']
|
||||
const onBeforeRouteLeave: typeof import('vue-router')['onBeforeRouteLeave']
|
||||
const onBeforeRouteUpdate: typeof import('vue-router')['onBeforeRouteUpdate']
|
||||
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
|
||||
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
|
||||
const onDeactivated: typeof import('vue')['onDeactivated']
|
||||
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
|
||||
const onMounted: typeof import('vue')['onMounted']
|
||||
const onRenderTracked: typeof import('vue')['onRenderTracked']
|
||||
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
|
||||
const onScopeDispose: typeof import('vue')['onScopeDispose']
|
||||
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
|
||||
const onUnmounted: typeof import('vue')['onUnmounted']
|
||||
const onUpdated: typeof import('vue')['onUpdated']
|
||||
const onWatcherCleanup: typeof import('vue')['onWatcherCleanup']
|
||||
const provide: typeof import('vue')['provide']
|
||||
const reactive: typeof import('vue')['reactive']
|
||||
const readonly: typeof import('vue')['readonly']
|
||||
const ref: typeof import('vue')['ref']
|
||||
const resolveComponent: typeof import('vue')['resolveComponent']
|
||||
const shallowReactive: typeof import('vue')['shallowReactive']
|
||||
const shallowReadonly: typeof import('vue')['shallowReadonly']
|
||||
const shallowRef: typeof import('vue')['shallowRef']
|
||||
const toRaw: typeof import('vue')['toRaw']
|
||||
const toRef: typeof import('vue')['toRef']
|
||||
const toRefs: typeof import('vue')['toRefs']
|
||||
const toValue: typeof import('vue')['toValue']
|
||||
const triggerRef: typeof import('vue')['triggerRef']
|
||||
const unref: typeof import('vue')['unref']
|
||||
const useAttrs: typeof import('vue')['useAttrs']
|
||||
const useCssModule: typeof import('vue')['useCssModule']
|
||||
const useCssVars: typeof import('vue')['useCssVars']
|
||||
const useHead: typeof import('unhead')['useHead']
|
||||
const useHeadSafe: typeof import('unhead')['useHeadSafe']
|
||||
const useId: typeof import('vue')['useId']
|
||||
const useLink: typeof import('vue-router')['useLink']
|
||||
const useModel: typeof import('vue')['useModel']
|
||||
const useRoute: typeof import('vue-router')['useRoute']
|
||||
const useRouter: typeof import('vue-router')['useRouter']
|
||||
const useSeoMeta: typeof import('unhead')['useSeoMeta']
|
||||
const useServerHead: typeof import('unhead')['useServerHead']
|
||||
const useServerHeadSafe: typeof import('unhead')['useServerHeadSafe']
|
||||
const useServerSeoMeta: typeof import('unhead')['useServerSeoMeta']
|
||||
const useSlots: typeof import('vue')['useSlots']
|
||||
const useTemplateRef: typeof import('vue')['useTemplateRef']
|
||||
const watch: typeof import('vue')['watch']
|
||||
const watchEffect: typeof import('vue')['watchEffect']
|
||||
const watchPostEffect: typeof import('vue')['watchPostEffect']
|
||||
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
|
||||
}
|
||||
// for type re-export
|
||||
declare global {
|
||||
// @ts-ignore
|
||||
export type { Component, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue'
|
||||
import('vue')
|
||||
}
|
||||
Vendored
+1
@@ -10,6 +10,7 @@ declare module 'vue' {
|
||||
Button: typeof import('primevue/button')['default']
|
||||
Card: typeof import('primevue/card')['default']
|
||||
ChatComponent: typeof import('./src/components/ChatComponent.vue')['default']
|
||||
ChatSubscribeWebPush: typeof import('./src/components/ChatSubscribeWebPush.vue')['default']
|
||||
Checkbox: typeof import('primevue/checkbox')['default']
|
||||
CreateActionsSection: typeof import('./src/components/create/CreateActionsSection.vue')['default']
|
||||
CreateMessageDeliveryMethodSection: typeof import('./src/components/create/CreateMessageDeliveryMethodSection.vue')['default']
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"@primevue/forms": "^4.2.1",
|
||||
"@primevue/themes": "^4.2.1",
|
||||
"@tanstack/vue-query": "^5.60.6",
|
||||
"@unhead/vue": "^1.11.13",
|
||||
"events": "^3.3.0",
|
||||
"md5": "^2.3.0",
|
||||
"pinia": "^2.2.6",
|
||||
@@ -33,6 +34,7 @@
|
||||
"svgo": "^3.3.2",
|
||||
"tailwind-scrollbar": "^3.1.0",
|
||||
"tailwindcss-primeui": "^0.3.4",
|
||||
"unhead": "^1.11.13",
|
||||
"vue": "^3.5.12",
|
||||
"vue-query": "^1.26.0",
|
||||
"vue-router": "^4.4.5"
|
||||
@@ -62,6 +64,7 @@
|
||||
"prettier": "^3.3.3",
|
||||
"tailwindcss": "^3.4.14",
|
||||
"typescript": "~5.6.3",
|
||||
"unplugin-auto-import": "^0.18.6",
|
||||
"unplugin-vue-components": "^0.27.4",
|
||||
"vite": "^5.4.10",
|
||||
"vite-plugin-vue-devtools": "^7.5.4",
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
MessageDocument,
|
||||
WebPushSubscriptionDocument,
|
||||
PublicSettingsDocument,
|
||||
UserChatSettingsDocument,
|
||||
} from '@hereconnect/types'
|
||||
|
||||
export const qrCodeDbRemote = new PouchDB<QRCodeDocument>(`${import.meta.env.VITE_API_URL}/qr`, {
|
||||
@@ -15,12 +16,11 @@ export const qrCodeDbLocal = new PouchDB<QRCodeDocument>('qr')
|
||||
|
||||
export const messagesDbLocal = new PouchDB<MessageDocument>('messages')
|
||||
|
||||
export const webPushSubscriptionsDbRemote = new PouchDB<WebPushSubscriptionDocument>(
|
||||
`${import.meta.env.VITE_API_URL}/web_push_subscriptions`,
|
||||
{
|
||||
skip_setup: true,
|
||||
},
|
||||
)
|
||||
export const webPushSubscriptionsDbRemote = new PouchDB<
|
||||
WebPushSubscriptionDocument<PushSubscriptionJSON>
|
||||
>(`${import.meta.env.VITE_API_URL}/web_push_subscriptions`, {
|
||||
skip_setup: true,
|
||||
})
|
||||
|
||||
export const publicSettingsDbRemote = new PouchDB<PublicSettingsDocument>(
|
||||
`${import.meta.env.VITE_API_URL}/public_settings`,
|
||||
@@ -35,3 +35,10 @@ export const messagesDbRemote = new PouchDB<MessageDocument>(
|
||||
skip_setup: true,
|
||||
},
|
||||
)
|
||||
|
||||
export const userChatSettingsDbRemote = new PouchDB<UserChatSettingsDocument>(
|
||||
`${import.meta.env.VITE_API_URL}/user_chat_settings`,
|
||||
{
|
||||
skip_setup: true,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { getUserUuid } from '@/utils/getUserUuid'
|
||||
import { getBrowserUuid } from '@/utils/getBrowserUuid'
|
||||
import { userChatSettingsDbRemote } from '@/api/dbs'
|
||||
import type { UserChatSettingsDocument } from '@hereconnect/types'
|
||||
|
||||
export const getUserChatSettingsDocument = ({
|
||||
chat,
|
||||
qr_code_uri,
|
||||
user_chat_role,
|
||||
}: {
|
||||
chat: string
|
||||
qr_code_uri: string
|
||||
user_chat_role: UserChatSettingsDocument['user_chat_role']
|
||||
}) => {
|
||||
return userChatSettingsDbRemote.get(
|
||||
`user_chat_settings:${qr_code_uri}:${chat}:${user_chat_role}:${getUserUuid()}`,
|
||||
)
|
||||
}
|
||||
|
||||
export const saveUserChatSettings = async ({
|
||||
chat,
|
||||
qr_code_uri,
|
||||
user_chat_role,
|
||||
is_push_notification_enabled,
|
||||
}: {
|
||||
chat: string
|
||||
qr_code_uri: string
|
||||
user_chat_role: UserChatSettingsDocument['user_chat_role']
|
||||
is_push_notification_enabled: boolean
|
||||
}) => {
|
||||
try {
|
||||
const user_uuid = getUserUuid()
|
||||
const browser_uuid = getBrowserUuid()
|
||||
const _id = `user_chat_settings:${qr_code_uri}:${chat}:${user_chat_role}:${user_uuid}`
|
||||
const result = await userChatSettingsDbRemote.upsert(
|
||||
_id,
|
||||
(doc): UserChatSettingsDocument | false => {
|
||||
const isNotChanged = doc.is_push_notification_enabled === is_push_notification_enabled
|
||||
if (isNotChanged) {
|
||||
return false
|
||||
}
|
||||
|
||||
const updated_at = new Date().toISOString()
|
||||
|
||||
return Object.assign(doc, {
|
||||
_id,
|
||||
type: 'user_chat_settings',
|
||||
qr_code_uri,
|
||||
browser_uuid,
|
||||
user_uuid,
|
||||
user_chat_role,
|
||||
chat,
|
||||
is_push_notification_enabled,
|
||||
created_at: doc.created_at ?? updated_at,
|
||||
updated_at,
|
||||
} satisfies UserChatSettingsDocument)
|
||||
},
|
||||
)
|
||||
console.log('Настройки успешно сохранены', result)
|
||||
} catch (error) {
|
||||
console.error('Ошибка сохранения настроек:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,21 @@ import { publicSettingsDbRemote, webPushSubscriptionsDbRemote } from '@/api/dbs'
|
||||
import { getUserUuid } from '@/utils/getUserUuid'
|
||||
import { getBrowserUuid } from '@/utils/getBrowserUuid'
|
||||
|
||||
export const getWebPushSubscriptionDocument = async () => {
|
||||
const type = 'web_push_subscription'
|
||||
const user_uuid = getUserUuid()
|
||||
const browser_uuid = getBrowserUuid()
|
||||
const _id = `${type}:${user_uuid}:${browser_uuid}`
|
||||
return webPushSubscriptionsDbRemote.get(_id)
|
||||
}
|
||||
|
||||
export const saveWebPushSubscription = async (subscription: PushSubscription) => {
|
||||
const type = 'web_push_subscription'
|
||||
const user_uuid = getUserUuid()
|
||||
const browser_uuid = getBrowserUuid()
|
||||
const _id = `${type}:${user_uuid}:${browser_uuid}`
|
||||
const created_at = new Date().toISOString()
|
||||
const webPushSubscriptionDoc: WebPushSubscriptionDocument = {
|
||||
const webPushSubscriptionDoc: WebPushSubscriptionDocument<PushSubscriptionJSON> = {
|
||||
_id,
|
||||
type,
|
||||
user_uuid,
|
||||
@@ -20,7 +28,7 @@ export const saveWebPushSubscription = async (subscription: PushSubscription) =>
|
||||
try {
|
||||
const { rev } = await webPushSubscriptionsDbRemote.upsert(
|
||||
_id,
|
||||
(doc): WebPushSubscriptionDocument | false => {
|
||||
(doc): WebPushSubscriptionDocument<PushSubscriptionJSON> | false => {
|
||||
webPushSubscriptionDoc._rev = doc._rev
|
||||
const isNotChanged =
|
||||
JSON.stringify(webPushSubscriptionDoc.subscription) === JSON.stringify(doc.subscription)
|
||||
@@ -37,6 +45,7 @@ export const saveWebPushSubscription = async (subscription: PushSubscription) =>
|
||||
return webPushSubscriptionDoc
|
||||
} catch (error) {
|
||||
console.error('Ошибка сохранения подписки:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,16 +24,25 @@
|
||||
<slot name="endOfMessages" :count="messages.length"></slot>
|
||||
</div>
|
||||
|
||||
<!-- Форма отправки сообщений -->
|
||||
<form @submit.prevent="sendMessage" class="flex gap-2 items-center p-4" ref="form">
|
||||
<InputText
|
||||
id="newMessage"
|
||||
v-model="newMessage"
|
||||
class="flex-1"
|
||||
placeholder="Напишите сообщение"
|
||||
/>
|
||||
<Button type="submit" icon="pi pi-send" class="p-button-md" :disabled="!newMessage.trim()" />
|
||||
</form>
|
||||
<div class="flex gap-3 p-4 pt-0 flex-col-reverse">
|
||||
<!-- Форма отправки сообщений -->
|
||||
<form @submit.prevent="sendMessage" class="flex gap-2 items-center" ref="form">
|
||||
<InputText
|
||||
id="newMessage"
|
||||
v-model="newMessage"
|
||||
class="flex-1"
|
||||
placeholder="Напишите сообщение"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
icon="pi pi-send"
|
||||
class="p-button-md"
|
||||
:disabled="!newMessage.trim()"
|
||||
/>
|
||||
</form>
|
||||
|
||||
<ChatSubscribeWebPush :qr_code_uri :chat :user_chat_role="userRole" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
<template>
|
||||
<div class="text-sm">
|
||||
<div class="flex items-center gap-2">
|
||||
<div v-if="isPending" class="w-5 h-5">
|
||||
<ProgressSpinner style="width: 100%; height: 100%" strokeWidth="8" fill="transparent" />
|
||||
</div>
|
||||
<Checkbox v-else v-model="enabled" inputId="webPush" name="delivery" binary />
|
||||
|
||||
<label for="webPush">Показать уведомление, когда придет ответ</label>
|
||||
</div>
|
||||
|
||||
<!-- Инструкции для iOS -->
|
||||
<div
|
||||
v-if="showRequireStandaloneInstructionsForIOS"
|
||||
class="bg-yellow-100 text-yellow-800 p-4 rounded my-4"
|
||||
>
|
||||
<p class="mb-2">Чтобы включить уведомления, добавьте это приложение на главный экран:</p>
|
||||
<ul class="list-disc pl-5">
|
||||
<li class="mb-1">
|
||||
Нажмите
|
||||
<strong class="font-semibold">
|
||||
"<img
|
||||
src="@/assets/icons/apple-share.svg?url"
|
||||
alt="Поделиться"
|
||||
class="h-7 -mt-2 inline-block"
|
||||
/>"
|
||||
</strong>
|
||||
внизу экрана
|
||||
</li>
|
||||
<li class="mb-1">
|
||||
Выберите
|
||||
<strong class="inline-flex items-baseline font-semibold">
|
||||
<span class="me-1">"На экран «Домой»</span>
|
||||
<img
|
||||
src="@/assets/icons/apple-system-plus.svg?url"
|
||||
alt=""
|
||||
class="h-4 inline-block self-center"
|
||||
/>"
|
||||
</strong>
|
||||
</li>
|
||||
<li>Откройте приложение с главного экрана и повторите попытку.</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- Ошибка разрешений -->
|
||||
<p v-else-if="isError" class="text-red-500 mb-2">{{ error?.message || error }}<br /></p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useMutation } from '@tanstack/vue-query'
|
||||
import {
|
||||
getVapidPublicKey,
|
||||
getWebPushSubscriptionDocument,
|
||||
saveWebPushSubscription,
|
||||
} from '@/api/webPush'
|
||||
import { getUserChatSettingsDocument } from '@/api/userChatSettings'
|
||||
import type { UserChatSettingsDocument } from '@hereconnect/types'
|
||||
import { isNotFoundError } from '@/api/PouchDB'
|
||||
import { saveUserChatSettings } from '@/api/userChatSettings'
|
||||
|
||||
// Проверки iOS и запуска из главного экрана
|
||||
const isIOS = computed(
|
||||
() => /iPad|iPhone|iPod/.test(navigator.userAgent) && !('MSStream' in window && window.MSStream),
|
||||
)
|
||||
const isStandalone = computed(() => 'standalone' in window.navigator && window.navigator.standalone)
|
||||
|
||||
const { qr_code_uri, chat, user_chat_role } = defineProps<{
|
||||
qr_code_uri: UserChatSettingsDocument['qr_code_uri']
|
||||
chat: UserChatSettingsDocument['chat']
|
||||
user_chat_role: UserChatSettingsDocument['user_chat_role']
|
||||
}>()
|
||||
|
||||
const enabled = ref<boolean>(false)
|
||||
|
||||
const subscribeOptionsPromise = getVapidPublicKey().then((applicationServerKey) => ({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey,
|
||||
}))
|
||||
|
||||
// Функция запроса разрешений и подписки
|
||||
async function requestNotificationPermission() {
|
||||
if (!('Notification' in window)) {
|
||||
throw new Error(
|
||||
isIOS.value && !isStandalone.value
|
||||
? 'Добавьте приложение на главный экран, чтобы использовать уведомления.'
|
||||
: 'Уведомления не поддерживаются этим браузером.',
|
||||
)
|
||||
}
|
||||
|
||||
const permission = await Notification.requestPermission()
|
||||
if (permission !== 'granted') {
|
||||
throw new Error(`Разрешение на уведомления не предоставлено: ${permission}`)
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker.ready
|
||||
let subscription: PushSubscription | null = null
|
||||
|
||||
try {
|
||||
subscription = await registration.pushManager.subscribe(await subscribeOptionsPromise)
|
||||
} catch (error) {
|
||||
subscription = await registration.pushManager.getSubscription()
|
||||
if (!subscription) {
|
||||
throw error
|
||||
}
|
||||
await subscription.unsubscribe()
|
||||
subscription = await registration.pushManager.subscribe(await subscribeOptionsPromise)
|
||||
}
|
||||
|
||||
return saveWebPushSubscription(subscription)
|
||||
}
|
||||
|
||||
const getPushSubscription = async () => {
|
||||
try {
|
||||
if ('serviceWorker' in navigator && 'PushManager' in window) {
|
||||
const registration = await navigator.serviceWorker.ready
|
||||
|
||||
const permission = await registration.pushManager.permissionState(
|
||||
await subscribeOptionsPromise,
|
||||
)
|
||||
console.debug('permission', permission)
|
||||
if (permission === 'prompt') {
|
||||
return
|
||||
}
|
||||
if (permission !== 'granted') {
|
||||
throw new Error(`Разрешение на уведомления не предоставлено: ${permission}`)
|
||||
}
|
||||
|
||||
const subscription = await registration.pushManager.getSubscription()
|
||||
if (subscription) {
|
||||
console.debug('Уже есть активная подписка:', subscription)
|
||||
return subscription
|
||||
} else {
|
||||
console.debug('Нет активной подписки на Push-уведомления.')
|
||||
}
|
||||
} else {
|
||||
console.warn('Push уведомления или Service Worker не поддерживаются в этом браузере.')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Произошла ошибка при получении подписки:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const stage = ref<'receivePushSubscription' | 'createPushSubscription' | 'removePushSubscription'>(
|
||||
'receivePushSubscription',
|
||||
)
|
||||
|
||||
// Хуки для состояния запроса
|
||||
const { isPending, isError, error, mutate } = useMutation({
|
||||
mutationKey: [stage],
|
||||
mutationFn: async () => {
|
||||
console.debug(stage.value)
|
||||
try {
|
||||
if (stage.value === 'receivePushSubscription') {
|
||||
const chatSettingsDocument = await getUserChatSettingsDocument({
|
||||
qr_code_uri,
|
||||
chat,
|
||||
user_chat_role,
|
||||
}).catch((error) => {
|
||||
if (!isNotFoundError(error)) throw error
|
||||
})
|
||||
if (chatSettingsDocument && chatSettingsDocument.is_push_notification_enabled) {
|
||||
const [subscription, subscriptionDocument] = await Promise.all([
|
||||
getPushSubscription(),
|
||||
getWebPushSubscriptionDocument().catch((error) => {
|
||||
if (!isNotFoundError(error)) throw error
|
||||
}),
|
||||
])
|
||||
if (subscription) {
|
||||
if (!subscriptionDocument) {
|
||||
await saveWebPushSubscription(subscription)
|
||||
}
|
||||
enabled.value = true
|
||||
stage.value = 'removePushSubscription'
|
||||
} else {
|
||||
stage.value = 'createPushSubscription'
|
||||
enabled.value = false
|
||||
}
|
||||
} else {
|
||||
stage.value = 'createPushSubscription'
|
||||
}
|
||||
} else if (stage.value === 'createPushSubscription') {
|
||||
await requestNotificationPermission()
|
||||
await saveUserChatSettings({
|
||||
qr_code_uri,
|
||||
chat,
|
||||
user_chat_role,
|
||||
is_push_notification_enabled: true,
|
||||
})
|
||||
} else if (stage.value === 'removePushSubscription') {
|
||||
await saveUserChatSettings({
|
||||
qr_code_uri,
|
||||
chat,
|
||||
user_chat_role,
|
||||
is_push_notification_enabled: false,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
enabled.value = false
|
||||
throw error
|
||||
}
|
||||
return null
|
||||
},
|
||||
retry: false,
|
||||
})
|
||||
|
||||
watch(
|
||||
[() => stage.value, () => enabled.value],
|
||||
() => {
|
||||
if (stage.value === 'removePushSubscription') {
|
||||
if (!enabled.value) mutate()
|
||||
} else if (stage.value === 'createPushSubscription') {
|
||||
if (enabled.value) mutate()
|
||||
} else {
|
||||
mutate()
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
const showRequireStandaloneInstructionsForIOS = computed(
|
||||
() => isError.value && isIOS.value && !isStandalone.value && enabled.value,
|
||||
)
|
||||
</script>
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createHead } from '@unhead/vue'
|
||||
import { VueQueryPlugin, type VueQueryPluginOptions } from '@tanstack/vue-query'
|
||||
import { createPinia } from 'pinia'
|
||||
// import { createPinia } from 'pinia'
|
||||
import PouchDB from '@/api/PouchDB'
|
||||
|
||||
import PrimeVue from 'primevue/config'
|
||||
@@ -39,14 +40,17 @@ const vueQueryPluginOptions: VueQueryPluginOptions = {
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
refetchOnWindowFocus: false,
|
||||
retryOnMount: false,
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const head = createHead()
|
||||
app.use(head)
|
||||
app.use(VueQueryPlugin, vueQueryPluginOptions)
|
||||
app.use(createPinia())
|
||||
// app.use(createPinia())
|
||||
app.use(router)
|
||||
app.use(PrimeVue, {
|
||||
theme: {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"include": ["./components.d.ts", "env.d.ts", "src/**/*", "src/**/*.vue"],
|
||||
"exclude": ["src/**/__tests__/*"],
|
||||
"files": ["./components.d.ts"],
|
||||
"files": ["./components.d.ts", "./auto-imports.d.ts"],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
|
||||
@@ -5,11 +5,16 @@ import vue from '@vitejs/plugin-vue'
|
||||
import vueDevTools from 'vite-plugin-vue-devtools'
|
||||
import Components from 'unplugin-vue-components/vite'
|
||||
import { PrimeVueResolver } from '@primevue/auto-import-resolver'
|
||||
import AutoImport from 'unplugin-auto-import/vite'
|
||||
import { unheadComposablesImports } from 'unhead'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
vue(),
|
||||
AutoImport({
|
||||
imports: ['vue', 'vue-router', unheadComposablesImports[0]],
|
||||
}),
|
||||
Components({
|
||||
resolvers: [PrimeVueResolver()],
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { type BaseDocument } from "./BaseDocument";
|
||||
import { MessageDocument } from "./MessageDocument";
|
||||
|
||||
/**
|
||||
* Интерфейс для документа настройки чата.
|
||||
* Используется для хранения настроек чата пользователя.
|
||||
*/
|
||||
export interface UserChatSettingsDocument extends BaseDocument {
|
||||
/** Тип документа, всегда 'message' */
|
||||
type: "user_chat_settings";
|
||||
|
||||
/** Идентификатор QR‑кода, к которому относится сообщение */
|
||||
qr_code_uri: string;
|
||||
|
||||
/** Идентификатор чата для связывания сообщений */
|
||||
chat: string;
|
||||
|
||||
user_chat_role: MessageDocument["from"];
|
||||
|
||||
/** Идентификатор пользователя, отправившего сообщение */
|
||||
user_uuid: string;
|
||||
|
||||
/** Идентификатор браузера, отправившего сообщение */
|
||||
browser_uuid: string;
|
||||
|
||||
/** Включены ли push-уведомления */
|
||||
is_push_notification_enabled: boolean;
|
||||
|
||||
/** Дата последнего обновления */
|
||||
updated_at?: string;
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
import type { BaseDocument } from "./BaseDocument";
|
||||
import type { PushSubscription } from "web-push";
|
||||
|
||||
export interface WebPushSubscriptionDocument extends BaseDocument {
|
||||
export interface WebPushSubscriptionDocument<
|
||||
Subscription extends PushSubscription | PushSubscriptionJSON,
|
||||
> extends BaseDocument {
|
||||
_id: string; // Формат: "web_push_subscription:<user_uuid>:<browser_uuid>"
|
||||
type: "web_push_subscription";
|
||||
user_uuid: string; // UUID пользователя, связанного с подпиской
|
||||
browser_uuid: string; // UUID браузера, связанного с подпиской
|
||||
subscription: PushSubscription;
|
||||
subscription: Subscription;
|
||||
created_at: string; // Дата создания подписки в ISO формате
|
||||
updated_at?: string; // Дата последнего обновления подписки
|
||||
}
|
||||
|
||||
@@ -4,4 +4,5 @@ export * from "./PublicSettingsDocument";
|
||||
export * from "./QRCodeDocument";
|
||||
export * from "./ServerSettingsDocument";
|
||||
export * from "./UserDocument";
|
||||
export * from "./UserChatSettingsDocument";
|
||||
export * from "./WebPushSubscriptionDocument";
|
||||
|
||||
Generated
+142
-1
@@ -25,6 +25,9 @@ importers:
|
||||
'@tanstack/vue-query':
|
||||
specifier: ^5.60.6
|
||||
version: 5.61.5(vue@3.5.13)
|
||||
'@unhead/vue':
|
||||
specifier: ^1.11.13
|
||||
version: 1.11.13(vue@3.5.13)
|
||||
events:
|
||||
specifier: ^3.3.0
|
||||
version: 3.3.0
|
||||
@@ -61,6 +64,9 @@ importers:
|
||||
tailwindcss-primeui:
|
||||
specifier: ^0.3.4
|
||||
version: 0.3.4(tailwindcss@3.4.15)
|
||||
unhead:
|
||||
specifier: ^1.11.13
|
||||
version: 1.11.13
|
||||
vue:
|
||||
specifier: ^3.5.12
|
||||
version: 3.5.13(typescript@5.6.3)
|
||||
@@ -143,6 +149,9 @@ importers:
|
||||
typescript:
|
||||
specifier: ~5.6.3
|
||||
version: 5.6.3
|
||||
unplugin-auto-import:
|
||||
specifier: ^0.18.6
|
||||
version: 0.18.6
|
||||
unplugin-vue-components:
|
||||
specifier: ^0.27.4
|
||||
version: 0.27.5(vue@3.5.13)
|
||||
@@ -1989,6 +1998,39 @@ packages:
|
||||
resolution: {integrity: sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==}
|
||||
dev: true
|
||||
|
||||
/@unhead/dom@1.11.13:
|
||||
resolution: {integrity: sha512-8Bpo3e50i49/z0TMiskQk3OqUVJpWOO0cnEEydJeFnjsPczDH76H3mWLvB11cv1B/rjLdBiPgui7yetFta5LCw==}
|
||||
dependencies:
|
||||
'@unhead/schema': 1.11.13
|
||||
'@unhead/shared': 1.11.13
|
||||
dev: false
|
||||
|
||||
/@unhead/schema@1.11.13:
|
||||
resolution: {integrity: sha512-fIpQx6GCpl99l4qJXsPqkXxO7suMccuLADbhaMSkeXnVEi4ZIle+l+Ri0z+GHAEpJj17FMaQdO5n9FMSOMUxkw==}
|
||||
dependencies:
|
||||
hookable: 5.5.3
|
||||
zhead: 2.2.4
|
||||
dev: false
|
||||
|
||||
/@unhead/shared@1.11.13:
|
||||
resolution: {integrity: sha512-EiJ3nsEtf6dvZ6OwVYrrrrCUl4ZE/9GTjpexEMti8EJXweSuL7SifNNXtIFk7UMoM0ULYxb7K/AKQV/odwoZyQ==}
|
||||
dependencies:
|
||||
'@unhead/schema': 1.11.13
|
||||
dev: false
|
||||
|
||||
/@unhead/vue@1.11.13(vue@3.5.13):
|
||||
resolution: {integrity: sha512-s5++LqsNM01rkMQwtc4W19cP1fXC81o4YMyL+Kaqh9X0OPLeWnjONAh0U/Z2CIXBqhJHI+DoNXmDACXyuWPPxg==}
|
||||
peerDependencies:
|
||||
vue: '>=2.7 || >=3'
|
||||
dependencies:
|
||||
'@unhead/schema': 1.11.13
|
||||
'@unhead/shared': 1.11.13
|
||||
defu: 6.1.4
|
||||
hookable: 5.5.3
|
||||
unhead: 1.11.13
|
||||
vue: 3.5.13(typescript@5.6.3)
|
||||
dev: false
|
||||
|
||||
/@vitejs/plugin-vue@5.2.1(vite@5.4.11)(vue@3.5.13):
|
||||
resolution: {integrity: sha512-cxh314tzaWwOLqVes2gnnCtvBDcM1UMdn+iFR+UjAn411dPT3tOmqrJjbMd7koZpMAmBM/GqeV4n9ge7JSiJJQ==}
|
||||
engines: {node: ^18.0.0 || >=20.0.0}
|
||||
@@ -3005,6 +3047,10 @@ packages:
|
||||
engines: {node: '>=12'}
|
||||
dev: true
|
||||
|
||||
/defu@6.1.4:
|
||||
resolution: {integrity: sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==}
|
||||
dev: false
|
||||
|
||||
/delayed-stream@1.0.0:
|
||||
resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
|
||||
engines: {node: '>=0.4.0'}
|
||||
@@ -3176,6 +3222,11 @@ packages:
|
||||
engines: {node: '>=10'}
|
||||
dev: true
|
||||
|
||||
/escape-string-regexp@5.0.0:
|
||||
resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}
|
||||
engines: {node: '>=12'}
|
||||
dev: true
|
||||
|
||||
/eslint-config-prettier@9.1.0(eslint@8.57.1):
|
||||
resolution: {integrity: sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==}
|
||||
hasBin: true
|
||||
@@ -3547,6 +3598,17 @@ packages:
|
||||
bser: 2.1.1
|
||||
dev: true
|
||||
|
||||
/fdir@6.4.2(picomatch@4.0.2):
|
||||
resolution: {integrity: sha512-KnhMXsKSPZlAhp7+IjUkRZKPb4fUyccpDrdFXbi4QL1qkmFh9kVY09Yox+n4MaOb3lHZ1Tv829C3oaaXoMYPDQ==}
|
||||
peerDependencies:
|
||||
picomatch: ^3 || ^4
|
||||
peerDependenciesMeta:
|
||||
picomatch:
|
||||
optional: true
|
||||
dependencies:
|
||||
picomatch: 4.0.2
|
||||
dev: true
|
||||
|
||||
/fetch-cookie@2.2.0:
|
||||
resolution: {integrity: sha512-h9AgfjURuCgA2+2ISl8GbavpUdR+WGAM2McW/ovn4tVccegp8ZqCKWSBR8uRdM8dDNlx5WdKRWxBYUwteLDCNQ==}
|
||||
dependencies:
|
||||
@@ -3782,7 +3844,6 @@ packages:
|
||||
|
||||
/hookable@5.5.3:
|
||||
resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==}
|
||||
dev: true
|
||||
|
||||
/html-encoding-sniffer@4.0.0:
|
||||
resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}
|
||||
@@ -4507,6 +4568,10 @@ packages:
|
||||
/js-tokens@4.0.0:
|
||||
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
||||
|
||||
/js-tokens@9.0.1:
|
||||
resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==}
|
||||
dev: true
|
||||
|
||||
/js-yaml@3.14.1:
|
||||
resolution: {integrity: sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==}
|
||||
hasBin: true
|
||||
@@ -5728,6 +5793,10 @@ packages:
|
||||
xmlchars: 2.2.0
|
||||
dev: true
|
||||
|
||||
/scule@1.3.0:
|
||||
resolution: {integrity: sha512-6FtHJEvt+pVMIB9IBY+IcCJ6Z5f1iQnytgyfKMhDKgmzYG+TeH/wx1y3l27rshSbLiSanrR9ffZDrEsmjlQF2g==}
|
||||
dev: true
|
||||
|
||||
/semver@6.3.1:
|
||||
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
|
||||
hasBin: true
|
||||
@@ -5899,6 +5968,12 @@ packages:
|
||||
acorn: 8.14.0
|
||||
dev: true
|
||||
|
||||
/strip-literal@2.1.1:
|
||||
resolution: {integrity: sha512-631UJ6O00eNGfMiWG78ck80dfBab8X6IVFB51jZK5Icd7XAs60Z5y7QdSd/wGIklnWvRbUNloVzhOKKmutxQ6Q==}
|
||||
dependencies:
|
||||
js-tokens: 9.0.1
|
||||
dev: true
|
||||
|
||||
/sucrase@3.35.0:
|
||||
resolution: {integrity: sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==}
|
||||
engines: {node: '>=16 || 14 >=14.17'}
|
||||
@@ -6045,6 +6120,14 @@ packages:
|
||||
resolution: {integrity: sha512-WiCJLEECkO18gwqIp6+hJg0//p23HXp4S+gGtAKu3mI2F2/sXC4FvHvXvB0zJVVaTPhx1/tOwdbRsa1sOBIKqQ==}
|
||||
dev: true
|
||||
|
||||
/tinyglobby@0.2.10:
|
||||
resolution: {integrity: sha512-Zc+8eJlFMvgatPZTl6A9L/yht8QqdmUNtURHaKZLmKBE12hNPSrqNkUp2cs3M/UKmNVVAMFQYSjYIVHDjW5zew==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
dependencies:
|
||||
fdir: 6.4.2(picomatch@4.0.2)
|
||||
picomatch: 4.0.2
|
||||
dev: true
|
||||
|
||||
/tinypool@0.7.0:
|
||||
resolution: {integrity: sha512-zSYNUlYSMhJ6Zdou4cJwo/p7w5nmAH17GRfU/ui3ctvjXFErXXkruT4MWW6poDeXgCaIBlGLrfU6TbTXxyGMww==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
@@ -6248,11 +6331,41 @@ packages:
|
||||
resolution: {integrity: sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==}
|
||||
dev: true
|
||||
|
||||
/unhead@1.11.13:
|
||||
resolution: {integrity: sha512-I7yyvqRfpPPzXuCG7HKZkgAWJDbzXDDEVyib4C/78HREqhNGHVSyo4TqX1h1xB5cx7WYc21HHDRT2/8YkqOy2w==}
|
||||
dependencies:
|
||||
'@unhead/dom': 1.11.13
|
||||
'@unhead/schema': 1.11.13
|
||||
'@unhead/shared': 1.11.13
|
||||
hookable: 5.5.3
|
||||
dev: false
|
||||
|
||||
/unicorn-magic@0.3.0:
|
||||
resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==}
|
||||
engines: {node: '>=18'}
|
||||
dev: true
|
||||
|
||||
/unimport@3.14.2:
|
||||
resolution: {integrity: sha512-FSxhbAylGGanyuTb3K0Ka3T9mnsD0+cRKbwOS11Li4Lh2whWS091e32JH4bIHrTckxlW9GnExAglADlxXjjzFw==}
|
||||
dependencies:
|
||||
'@rollup/pluginutils': 5.1.3
|
||||
acorn: 8.14.0
|
||||
escape-string-regexp: 5.0.0
|
||||
estree-walker: 3.0.3
|
||||
local-pkg: 0.5.1
|
||||
magic-string: 0.30.14
|
||||
mlly: 1.7.3
|
||||
pathe: 1.1.2
|
||||
picomatch: 4.0.2
|
||||
pkg-types: 1.2.1
|
||||
scule: 1.3.0
|
||||
strip-literal: 2.1.1
|
||||
tinyglobby: 0.2.10
|
||||
unplugin: 1.16.0
|
||||
transitivePeerDependencies:
|
||||
- rollup
|
||||
dev: true
|
||||
|
||||
/universalify@0.2.0:
|
||||
resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==}
|
||||
engines: {node: '>= 4.0.0'}
|
||||
@@ -6270,6 +6383,30 @@ packages:
|
||||
detect-node: 2.1.0
|
||||
dev: false
|
||||
|
||||
/unplugin-auto-import@0.18.6:
|
||||
resolution: {integrity: sha512-LMFzX5DtkTj/3wZuyG5bgKBoJ7WSgzqSGJ8ppDRdlvPh45mx6t6w3OcbExQi53n3xF5MYkNGPNR/HYOL95KL2A==}
|
||||
engines: {node: '>=14'}
|
||||
peerDependencies:
|
||||
'@nuxt/kit': ^3.2.2
|
||||
'@vueuse/core': '*'
|
||||
peerDependenciesMeta:
|
||||
'@nuxt/kit':
|
||||
optional: true
|
||||
'@vueuse/core':
|
||||
optional: true
|
||||
dependencies:
|
||||
'@antfu/utils': 0.7.10
|
||||
'@rollup/pluginutils': 5.1.3
|
||||
fast-glob: 3.3.2
|
||||
local-pkg: 0.5.1
|
||||
magic-string: 0.30.14
|
||||
minimatch: 9.0.5
|
||||
unimport: 3.14.2
|
||||
unplugin: 1.16.0
|
||||
transitivePeerDependencies:
|
||||
- rollup
|
||||
dev: true
|
||||
|
||||
/unplugin-vue-components@0.27.5(vue@3.5.13):
|
||||
resolution: {integrity: sha512-m9j4goBeNwXyNN8oZHHxvIIYiG8FQ9UfmKWeNllpDvhU7btKNNELGPt+o3mckQKuPwrE7e0PvCsx+IWuDSD9Vg==}
|
||||
engines: {node: '>=14'}
|
||||
@@ -6944,3 +7081,7 @@ packages:
|
||||
resolution: {integrity: sha512-GQHQqAopRhwU8Kt1DDM8NjibDXHC8eoh1erhGAJPEyveY9qqVeXvVikNKrDz69sHowPMorbPUrH/mx8c50eiBQ==}
|
||||
engines: {node: '>=18'}
|
||||
dev: true
|
||||
|
||||
/zhead@2.2.4:
|
||||
resolution: {integrity: sha512-8F0OI5dpWIA5IGG5NHUg9staDwz/ZPxZtvGVf01j7vHqSyZ0raHY+78atOVxRqb73AotX22uV1pXt3gYSstGag==}
|
||||
dev: false
|
||||
|
||||
@@ -11,35 +11,53 @@ const dbsSecurity = {
|
||||
},
|
||||
server_settings: {
|
||||
admins: { roles: ["_admin"] },
|
||||
qr: {
|
||||
admins: { roles: ["_admin"] },
|
||||
members: { roles: [] },
|
||||
|
||||
members: { roles: ["_admin"] },
|
||||
},
|
||||
public_settings: {
|
||||
admins: { roles: ["_admin"] },
|
||||
members: { roles: [] },
|
||||
},
|
||||
members: { roles: ["_admin"] },
|
||||
},
|
||||
qr: {
|
||||
admins: { roles: ["_admin"] },
|
||||
members: { roles: [] },
|
||||
},
|
||||
public_settings: {
|
||||
admins: { roles: ["_admin"] },
|
||||
members: { roles: [] },
|
||||
},
|
||||
user_chat_settings: {
|
||||
admins: { roles: ["_admin"] },
|
||||
members: { roles: [] },
|
||||
},
|
||||
};
|
||||
|
||||
export const up = async () => {
|
||||
for (const [dbName, dbSecurity] of Object.entries(dbsSecurity)) {
|
||||
await fetch(`${process.env.API_URL}/${dbName}`, {
|
||||
const responseCreateDb = await fetch(`${process.env.API_URL}/${dbName}`, {
|
||||
method: "PUT",
|
||||
});
|
||||
await fetch(`${process.env.API_URL}/${dbName}/_security`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(dbSecurity),
|
||||
});
|
||||
console.assert(
|
||||
(await responseCreateDb.json()).ok,
|
||||
`${dbName} create db error`,
|
||||
);
|
||||
const responseSetSecurity = await fetch(
|
||||
`${process.env.API_URL}/${dbName}/_security`,
|
||||
{
|
||||
method: "PUT",
|
||||
body: JSON.stringify(dbSecurity),
|
||||
},
|
||||
);
|
||||
console.assert(
|
||||
(await responseSetSecurity.json()).ok,
|
||||
`${dbName} security error`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const down = async () => {
|
||||
for (const dbName of Object.keys(dbsSecurity)) {
|
||||
await fetch(`${process.env.API_URL}/${dbName}`, {
|
||||
const responseDeleteDb = await fetch(`${process.env.API_URL}/${dbName}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
console.assert(
|
||||
(await responseDeleteDb.json()).ok,
|
||||
`${dbName} create db error`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
"contributors": [],
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"generate-keys": "node ./src/generate-keys.js",
|
||||
"generate-keys": "node src/generate-keys.ts",
|
||||
"test-send-notification": "node ./src/test-send-notification.js",
|
||||
"test-send-notification-cancel": "node ./src/test-send-notification-cancel.js"
|
||||
},
|
||||
|
||||
@@ -3,8 +3,10 @@ import type {
|
||||
MessageDocument,
|
||||
QRCodeDocument,
|
||||
ServerSettingsDocument,
|
||||
UserChatSettingsDocument,
|
||||
WebPushSubscriptionDocument,
|
||||
} from "@hereconnect/types";
|
||||
import { PushSubscription } from "web-push";
|
||||
|
||||
export interface ServiceDoc {
|
||||
_id: string;
|
||||
@@ -27,12 +29,11 @@ export const qrDb = new PouchDB<QRCodeDocument>(`${process.env.API_URL}/qr`, {
|
||||
skip_setup: true,
|
||||
});
|
||||
|
||||
export const webPushSubscriptionsDb = new PouchDB<WebPushSubscriptionDocument>(
|
||||
`${process.env.API_URL}/web_push_subscriptions`,
|
||||
{
|
||||
skip_setup: true,
|
||||
},
|
||||
);
|
||||
export const webPushSubscriptionsDb = new PouchDB<
|
||||
WebPushSubscriptionDocument<PushSubscription>
|
||||
>(`${process.env.API_URL}/web_push_subscriptions`, {
|
||||
skip_setup: true,
|
||||
});
|
||||
|
||||
export const { messagesDb, serviceDb } = (() => {
|
||||
const messagesDB = new PouchDB(messagesDbUrl, {
|
||||
@@ -44,3 +45,10 @@ export const { messagesDb, serviceDb } = (() => {
|
||||
serviceDb: messagesDB as PouchDB.Database<ServiceDoc>,
|
||||
} as const;
|
||||
})();
|
||||
|
||||
export const userChatSettingsDb = new PouchDB<UserChatSettingsDocument>(
|
||||
`${process.env.API_URL}/user_chat_settings`,
|
||||
{
|
||||
skip_setup: true,
|
||||
},
|
||||
);
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import webpush from "web-push";
|
||||
import PouchDB from "./PouchDB.js";
|
||||
import PouchDB from "./PouchDB";
|
||||
|
||||
if (!process.env.VAPID_SUBJECT) {
|
||||
throw new Error("VAPID_SUBJECT env is empty!");
|
||||
@@ -1,7 +1,12 @@
|
||||
import webpush from "web-push";
|
||||
|
||||
import { CouchDBChangesStream } from "@hereconnect/couchdb-changes-stream";
|
||||
import { qrDb, messagesDbUrl, webPushSubscriptionsDb } from "./dbs";
|
||||
import {
|
||||
qrDb,
|
||||
messagesDbUrl,
|
||||
webPushSubscriptionsDb,
|
||||
userChatSettingsDb,
|
||||
} from "./dbs";
|
||||
import { setupVapidDetails } from "./setupVapidDetails";
|
||||
import type { MessageDocument } from "@hereconnect/types";
|
||||
import { ServiceSeqTracker } from "./serviceSeqTracker";
|
||||
@@ -123,6 +128,82 @@ const start = async () => {
|
||||
}
|
||||
} else if (msgDoc.from === "owner") {
|
||||
console.log("FROM OWNER");
|
||||
const qrDoc = await qrDb.get(`qr_code:${msgDoc.qr_code_uri}`);
|
||||
const { rows: userChatSettingsRows } = await userChatSettingsDb.allDocs(
|
||||
{
|
||||
startkey: `user_chat_settings:${msgDoc.qr_code_uri}:${msgDoc.chat}:guest:`,
|
||||
endkey: `user_chat_settings:${msgDoc.qr_code_uri}:${msgDoc.chat}:guest:\uffff`,
|
||||
include_docs: true,
|
||||
},
|
||||
);
|
||||
for (const { doc: userChatSettingDoc } of userChatSettingsRows) {
|
||||
if (!userChatSettingDoc) {
|
||||
continue;
|
||||
}
|
||||
if (!userChatSettingDoc.is_push_notification_enabled) {
|
||||
console.log("PUSH NOTIFICATION DISABLED");
|
||||
continue;
|
||||
}
|
||||
|
||||
const { rows: subscriptionRows } =
|
||||
await webPushSubscriptionsDb.allDocs({
|
||||
startkey: `web_push_subscription:${userChatSettingDoc.user_uuid}:`,
|
||||
endkey: `web_push_subscription:${userChatSettingDoc.user_uuid}:\uffff`,
|
||||
include_docs: true,
|
||||
});
|
||||
|
||||
if (subscriptionRows.length === 0) {
|
||||
console.log("NO SUBSCRIPTIONS");
|
||||
} else {
|
||||
console.log(`sending to ${subscriptionRows.length} devices`);
|
||||
}
|
||||
|
||||
// for (const row of subscriptionRows) {
|
||||
// try {
|
||||
// const subscription = row.doc!.subscription;
|
||||
// const topic = `chat-${msgDoc.qr_code_uri}-${msgDoc.chat}`;
|
||||
// const timestamp = new Date(msgDoc.created_at).getTime();
|
||||
// const tag = `${topic}-${(timestamp - new Date(qrDoc.created_at).getTime()).toString(36)}`;
|
||||
//
|
||||
// const title = limitStringLengthWithEllipsis(
|
||||
// `${qrDoc.name}: новое сообщение`,
|
||||
// 53,
|
||||
// );
|
||||
// const body = limitStringLengthWithEllipsis(msgDoc.body, 470);
|
||||
//
|
||||
// const options: NotificationOptions & { timestamp: number } = {
|
||||
// icon: "/images/qr-code-logo-200x200.jpg",
|
||||
// body,
|
||||
// tag,
|
||||
// requireInteraction: true,
|
||||
// timestamp,
|
||||
// data: {
|
||||
// url: `/manage/${msgDoc.qr_code_uri}/chat/${msgDoc.chat}`,
|
||||
// payload: { tag },
|
||||
// },
|
||||
// } as const;
|
||||
//
|
||||
// await webpush.sendNotification(
|
||||
// subscription,
|
||||
// JSON.stringify({
|
||||
// type: "notification",
|
||||
// notification: {
|
||||
// title,
|
||||
// options,
|
||||
// },
|
||||
// }),
|
||||
// {
|
||||
// urgency: "high",
|
||||
// topic,
|
||||
// },
|
||||
// );
|
||||
// } catch (error) {
|
||||
// console.error(
|
||||
// `Error sending notification to ${row.id} - ${JSON.stringify(error)}`,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user