import { defineStore } from "pinia" import { ref } from "vue" import { checkLoggedIn, getAtk } from "@/stores/userinfo" import { buildRequestUrl, request } from "@/scripts/request" import { LocalNotifications } from "@capacitor/local-notifications" import { Capacitor } from "@capacitor/core" export const useNotifications = defineStore("notifications", () => { let socket: WebSocket let reconnectCount = 0 const loading = ref(false) const notifications = ref([]) const total = ref(0) async function list() { loading.value = true const res = await request( "identity", "/api/notifications?" + new URLSearchParams({ take: (25).toString(), offset: (0).toString() }), { headers: { Authorization: `Bearer ${await getAtk()}` } } ) if (res.status === 200) { const data = await res.json() notifications.value = data["data"] total.value = data["count"] } loading.value = false } function remove(idx: number) { notifications.value.splice(idx, 1) total.value-- } async function connect() { if (!(await checkLoggedIn())) return const uri = buildRequestUrl("identity", "/api/notifications/listen").replace("http", "ws") socket = new WebSocket(uri + `?tk=${await getAtk() as string}`) socket.addEventListener("open", (event) => { console.log("[NOTIFICATIONS] The listen websocket has been established... ", event.type) reconnectCount = 0 }) socket.addEventListener("close", (event) => { console.warn("[NOTIFICATIONS] The listen websocket is disconnected... ", event.reason, event.code) if (reconnectCount <= 3) { connect().then(() => { console.warn("[NOTIFICATIONS] Now reconnecting!") reconnectCount++ }) } }) socket.addEventListener("message", (event) => { const data = JSON.parse(event.data) if (!data.is_realtime) { notifications.value.push(data) total.value++ } if (Capacitor.getPlatform() === "web") { new Notification(data["subject"], { body: data["content"] }) } else { LocalNotifications.schedule({ notifications: [ { id: data["id"], title: data["subject"], body: data["content"] } ] }).then((res) => console.log(res)) } }) if (Capacitor.getPlatform() === "web") { await Notification.requestPermission() } else { await LocalNotifications.requestPermissions() } } function disconnect() { socket.close() } return { loading, notifications, total, list, remove, connect, disconnect } })