This repository has been archived on 2024-06-08. You can view files and clone it, but cannot push or open issues or pull requests.
SolarAgent/src/stores/channels.ts
2024-03-31 00:38:13 +08:00

68 lines
1.9 KiB
TypeScript

import { defineStore } from "pinia"
import { reactive, ref } from "vue"
import { checkLoggedIn, getAtk } from "@/stores/userinfo"
import { buildRequestUrl, request } from "@/scripts/request"
export const useChannels = defineStore("channels", () => {
let socket: WebSocket
const done = ref(false)
const show = reactive({
editor: false,
delete: false
})
const related = reactive<{ edit_to: any; delete_to: any }>({
edit_to: null,
delete_to: null
})
const available = ref<any[]>([])
const current = ref<any>(null)
const messages = ref<any[]>([])
async function list() {
if (!(await checkLoggedIn())) return
const res = await request("messaging", "/api/channels/me/available", {
headers: { Authorization: `Bearer ${await getAtk()}` }
})
if (res.status !== 200) {
throw new Error(await res.text())
} else {
available.value = await res.json()
}
}
async function connect() {
if (!(await checkLoggedIn())) return
const uri = buildRequestUrl("messaging", "/api/unified").replace("http", "ws")
socket = new WebSocket(uri + `?tk=${await getAtk() as string}`)
socket.addEventListener("open", (event) => {
console.log("[MESSAGING] The unified websocket has been established... ", event.type)
})
socket.addEventListener("close", (event) => {
console.warn("[MESSAGING] The unified websocket is disconnected... ", event.reason, event.code)
})
socket.addEventListener("message", (event) => {
const data = JSON.parse(event.data)
const payload = data["p"]
if (payload?.channel_id === current.value.id) {
switch (data["w"]) {
case "messages.new":
messages.value.unshift(payload)
}
}
})
}
function disconnect() {
socket.close()
}
return { done, show, related, available, current, messages, list, connect, disconnect }
})