2026-08-31 19:22:12 +03:00
|
|
|
import { Socket } from 'phoenix'
|
2023-04-04 21:17:54 -06:00
|
|
|
import { defineStore } from 'pinia'
|
2026-09-01 18:02:38 +03:00
|
|
|
|
2026-08-31 19:22:12 +03:00
|
|
|
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
|
|
|
|
|
import { useUsersStore } from 'src/stores/users.js'
|
2023-04-04 21:17:54 -06:00
|
|
|
|
2026-08-31 19:22:12 +03:00
|
|
|
// Maybe rename it to PhoenixSocket if we ever utilize this socket more
|
2023-04-04 21:17:54 -06:00
|
|
|
export const useShoutStore = defineStore('shout', {
|
|
|
|
|
state: () => ({
|
|
|
|
|
messages: [],
|
|
|
|
|
channel: { state: '' },
|
2026-01-06 16:22:52 +02:00
|
|
|
joined: false,
|
2026-08-31 19:22:12 +03:00
|
|
|
token: null,
|
|
|
|
|
socket: null,
|
2023-04-04 21:17:54 -06:00
|
|
|
}),
|
2026-08-31 19:22:12 +03:00
|
|
|
getters: {
|
2026-09-01 18:02:38 +03:00
|
|
|
token: () => useUsersStore().currentUser?.token,
|
2026-08-31 19:22:12 +03:00
|
|
|
},
|
2023-04-04 21:17:54 -06:00
|
|
|
actions: {
|
2026-08-31 19:22:12 +03:00
|
|
|
initializeSocket() {
|
|
|
|
|
if (this.token === null) return
|
|
|
|
|
if (!useInstanceCapabilitiesStore().shoutAvailable) return
|
|
|
|
|
if (this.socket !== null) throw new Error('Shout socket already exist!')
|
|
|
|
|
|
|
|
|
|
this.socket = new Socket('/socket', { params: { token: this.token } })
|
|
|
|
|
this.socket.connect()
|
|
|
|
|
},
|
|
|
|
|
initializeShout() {
|
|
|
|
|
const channel = this.socket.channel('chat:public')
|
|
|
|
|
|
2023-04-04 21:17:54 -06:00
|
|
|
channel.joinPush.receive('ok', () => {
|
|
|
|
|
this.joined = true
|
|
|
|
|
})
|
|
|
|
|
channel.onClose(() => {
|
|
|
|
|
this.joined = false
|
|
|
|
|
})
|
|
|
|
|
channel.onError(() => {
|
|
|
|
|
this.joined = false
|
|
|
|
|
})
|
|
|
|
|
channel.on('new_msg', (msg) => {
|
|
|
|
|
this.messages.push(msg)
|
|
|
|
|
this.messages = this.messages.slice(-19, 20)
|
|
|
|
|
})
|
|
|
|
|
channel.on('messages', ({ messages }) => {
|
|
|
|
|
this.messages = messages.slice(-19, 20)
|
|
|
|
|
})
|
|
|
|
|
channel.join()
|
|
|
|
|
this.channel = channel
|
2026-01-06 16:22:52 +02:00
|
|
|
},
|
2026-08-31 19:22:12 +03:00
|
|
|
disconnectSocket() {
|
|
|
|
|
this.socket?.disconnect()
|
|
|
|
|
this.socket = null
|
2026-09-01 18:02:38 +03:00
|
|
|
},
|
2026-01-06 16:22:52 +02:00
|
|
|
},
|
2023-04-04 21:17:54 -06:00
|
|
|
})
|