fix logout and save WS url.

This commit is contained in:
Miroslav Šedivý 2021-02-08 17:50:12 +01:00
parent 817ea28379
commit f2a9a33cb0
2 changed files with 24 additions and 9 deletions

View File

@ -14,11 +14,19 @@ export class NekoWebSocket extends EventEmitter<NekoWebSocketEvents> {
private _ws?: WebSocket
private _timeout?: NodeJS.Timeout
private _log: Logger
private _url: string
constructor() {
super()
this._log = new Logger('websocket')
this._url = ''
this.setUrl(location.href)
}
public setUrl(url: string) {
this._url = url.replace(/^http/, 'ws').replace(/\/+$/, '') + '/api/ws'
}
get supported() {
@ -29,14 +37,14 @@ export class NekoWebSocket extends EventEmitter<NekoWebSocketEvents> {
return typeof this._ws !== 'undefined' && this._ws.readyState === WebSocket.OPEN
}
public connect(url: string) {
public connect() {
if (this.connected) {
throw new Error('attempting to create websocket while connection open')
}
this.emit('connecting')
this._ws = new WebSocket(url)
this._ws = new WebSocket(this._url)
this._log.info(`connecting`)
this._ws.onopen = this.onConnected.bind(this)

View File

@ -153,6 +153,7 @@
public setUrl(url: string) {
const httpURL = url.replace(/^ws/, 'http').replace(/\/$|\/ws\/?$/, '')
this.api.setUrl(httpURL)
this.websocket.setUrl(httpURL)
}
public async login(id: string, secret: string) {
@ -162,7 +163,7 @@
await this.api.session.login({ id, secret })
Vue.set(this.state.connection, 'authenticated', true)
this.websocketConnect()
this.websocket.connect()
}
public async logout() {
@ -170,10 +171,16 @@
throw new Error('client not authenticated')
}
if (this.connected) {
this.websocketDisconnect()
}
try {
await this.api.session.logout()
} finally {
Vue.set(this.state.connection, 'authenticated', false)
}
}
public websocketConnect() {
if (!this.authenticated) {
@ -184,7 +191,7 @@
throw new Error('client already connected to websocket')
}
this.websocket.connect(this.api.url.replace(/^http/, 'ws') + '/api/ws')
this.websocket.connect()
}
public websocketDisconnect() {
@ -358,7 +365,7 @@
if (this.authenticated) {
setTimeout(() => {
try {
this.websocketConnect()
this.websocket.connect()
} catch (e) {}
}, 1000)
}
@ -427,7 +434,7 @@
// check if is user logged in
this.api.session.whoami().then(() => {
Vue.set(this.state.connection, 'authenticated', true)
this.websocketConnect()
this.websocket.connect()
})
// unmute on users first interaction