✨ Local Notifications
This commit is contained in:
81
src/stores/notifications.ts
Normal file
81
src/stores/notifications.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
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
|
||||
|
||||
const loading = ref(false)
|
||||
|
||||
const notifications = ref<any[]>([])
|
||||
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)
|
||||
})
|
||||
socket.addEventListener("close", (event) => {
|
||||
console.warn("[NOTIFICATIONS] The listen websocket is disconnected... ", event.reason, event.code)
|
||||
})
|
||||
socket.addEventListener("message", (event) => {
|
||||
const data = JSON.parse(event.data)
|
||||
notifications.value.push(data)
|
||||
total.value++
|
||||
|
||||
if (Capacitor.getPlatform() === "web") {
|
||||
new Notification(data["id"], {
|
||||
body: data["subject"]
|
||||
})
|
||||
} else {
|
||||
LocalNotifications.schedule({
|
||||
notifications: [
|
||||
{ id: data["id"], title: data["subject"], body: data["subject"] }
|
||||
]
|
||||
}).then((res) => console.log(res))
|
||||
}
|
||||
})
|
||||
|
||||
await Notification.requestPermission()
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
socket.close()
|
||||
}
|
||||
|
||||
return { loading, notifications, total, list, remove, connect, disconnect }
|
||||
})
|
Reference in New Issue
Block a user