Chat message send and read history

This commit is contained in:
2024-03-30 23:21:22 +08:00
parent 8bb9816cd0
commit a5efec89f2
7 changed files with 137 additions and 40 deletions

View File

@@ -1,9 +1,11 @@
import { defineStore } from "pinia"
import { reactive, ref } from "vue"
import { checkLoggedIn, getAtk } from "@/stores/userinfo"
import { request } from "@/scripts/request"
import { buildRequestUrl, request } from "@/scripts/request"
export const useChannels = defineStore("channels", () => {
let socket: WebSocket
const done = ref(false)
const show = reactive({
@@ -33,5 +35,34 @@ export const useChannels = defineStore("channels", () => {
}
}
return { done, show, related_to, available, current, messages, list }
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_to, available, current, messages, list, connect, disconnect }
})

View File

@@ -33,7 +33,7 @@ export async function checkLoggedIn(): Promise<boolean> {
export const useUserinfo = defineStore("userinfo", () => {
const userinfoHooks = {
after: [useRealms().list, useChannels().list]
after: [useRealms().list, useChannels().list, useChannels().connect]
}
const userinfo = ref(defaultUserinfo)