Files
tabby-web/src/services/appConnector.service.ts

73 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-06-19 23:01:22 +02:00
import { Buffer } from 'buffer'
2021-06-14 23:00:05 +02:00
import { Subject } from 'rxjs'
import { debounceTime } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
2021-06-19 23:01:22 +02:00
export class SocketProxy {
connect$ = new Subject<void>()
data$ = new Subject<Buffer>()
webSocket: WebSocket
initialBuffer: Buffer
constructor (...args) {
console.log('ws ctr', args)
this.initialBuffer = Buffer.from('')
}
connect (...args) {
console.log('ws connect', args)
this.webSocket = new WebSocket(`ws://${location.host}/api/1/gateway/tcp`)
this.webSocket.onopen = event => {
this.connect$.next()
this.connect$.complete()
this.webSocket.send(this.initialBuffer)
this.initialBuffer = Buffer.from('')
}
this.webSocket.onmessage = async event => {
this.data$.next(Buffer.from(await event.data.arrayBuffer()))
}
}
write (chunk: Buffer): void {
if (!this.webSocket.readyState) {
this.initialBuffer = Buffer.concat([this.initialBuffer, chunk])
} else {
this.webSocket.send(chunk)
}
}
close (error: Error): void {
console.warn('socket destroy', error)
}
}
2021-06-14 23:00:05 +02:00
@Injectable({ providedIn: 'root' })
export class AppConnectorService {
config: any
2021-06-19 23:01:22 +02:00
version: any
Socket = SocketProxy
2021-06-14 23:00:05 +02:00
private configUpdate = new Subject<string>()
constructor (private http: HttpClient) {
2021-06-15 23:43:23 +02:00
this.configUpdate.pipe(debounceTime(1000)).subscribe(async content => {
const result = await this.http.patch(`/api/1/configs/${this.config.id}`, { content }).toPromise()
Object.assign(this.config, result)
2021-06-14 23:00:05 +02:00
})
}
async loadConfig (): Promise<string> {
return this.config.content
}
async saveConfig (content: string): Promise<void> {
this.configUpdate.next(content)
2021-06-15 23:43:23 +02:00
this.config.content = content
2021-06-14 23:00:05 +02:00
}
2021-06-19 23:01:22 +02:00
getAppVersion (): string {
return this.version.version
}
2021-06-14 23:00:05 +02:00
}