This commit is contained in:
Eugene Pankov
2021-07-25 16:36:45 +02:00
parent 6a78032849
commit c8ee6832f3
57 changed files with 53 additions and 1003 deletions

View File

@@ -0,0 +1,201 @@
import { Buffer } from 'buffer'
import { Subject } from 'rxjs'
import { debounceTime } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
import { Injectable, Injector } from '@angular/core'
import { Config, Gateway, Version } from '../api'
import { LoginService } from './login.service'
import { CommonService } from './common.service'
export class SocketProxy {
connect$ = new Subject<void>()
data$ = new Subject<Uint8Array>()
error$ = new Subject<Error>()
close$ = new Subject<void>()
url: string
authToken: string
webSocket: WebSocket|null
initialBuffers: any[] = []
options: {
host: string
port: number
}
private appConnector: AppConnectorService
private loginService: LoginService
constructor (
injector: Injector,
) {
this.appConnector = injector.get(AppConnectorService)
this.loginService = injector.get(LoginService)
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
async connect (options: any): Promise<void> {
this.options = options
this.url = this.loginService.user.custom_connection_gateway
this.authToken = this.loginService.user.custom_connection_gateway_token
if (!this.url) {
try {
const gateway = await this.appConnector.chooseConnectionGateway()
this.url = gateway.url
this.authToken = gateway.auth_token
} catch (err) {
this.close(err)
return
}
}
try {
this.webSocket = new WebSocket(this.url)
} catch (err) {
this.close(err)
return
}
this.webSocket.onerror = err => {
this.close(new Error(`Failed to connect to the connection gateway at ${this.url}`))
return
}
this.webSocket.onmessage = async event => {
if (typeof(event.data) === 'string') {
this.handleServiceMessage(JSON.parse(event.data))
} else {
this.data$.next(Buffer.from(await event.data.arrayBuffer()))
}
}
this.webSocket.onclose = () => {
this.close()
}
}
handleServiceMessage (msg) {
if (msg._ === 'hello') {
this.sendServiceMessage({
_: 'hello',
version: 1,
auth_token: this.authToken,
})
} else if (msg._ === 'ready') {
this.sendServiceMessage({
_: 'connect',
host: this.options.host,
port: this.options.port,
})
} else if (msg._ === 'connected') {
this.connect$.next()
this.connect$.complete()
for (const b of this.initialBuffers) {
this.webSocket.send(b)
}
this.initialBuffers = []
} else if (msg._ === 'error') {
console.error('Connection gateway error', msg)
this.close(new Error(msg.details))
} else {
console.warn('Unknown service message', msg)
}
}
sendServiceMessage (msg) {
this.webSocket.send(JSON.stringify(msg))
}
write (chunk: Buffer): void {
if (!this.webSocket?.readyState) {
this.initialBuffers.push(chunk)
} else {
this.webSocket.send(chunk)
}
}
close (error?: Error): void {
this.webSocket?.close()
if (error) {
this.error$.next(error)
}
this.connect$.complete()
this.data$.complete()
this.error$.complete()
this.close$.next()
this.close$.complete()
}
}
@Injectable({ providedIn: 'root' })
export class AppConnectorService {
private configUpdate = new Subject<string>()
private config: Config
private version: Version
sockets: SocketProxy[] = []
constructor (
private injector: Injector,
private http: HttpClient,
private commonService: CommonService,
) {
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)
})
}
setState (config: Config, version: Version) {
this.config = config
this.version = version
}
async loadConfig (): Promise<string> {
return this.config.content
}
async saveConfig (content: string): Promise<void> {
this.configUpdate.next(content)
this.config.content = content
}
getAppVersion (): string {
return this.version.version
}
async getDistURL (): Promise<string> {
return await this.commonService.backendURL$ + '/app-dist'
}
getPluginsToLoad (): string[] {
const loadOrder = [
'tabby-core',
'tabby-settings',
'tabby-terminal',
'tabby-ssh',
'tabby-community-color-schemes',
'tabby-web',
]
return [
...loadOrder.filter(x => this.version.plugins.includes(x)),
...this.version.plugins.filter(x => !loadOrder.includes(x)),
]
}
createSocket () {
const socket = new SocketProxy(this.injector)
this.sockets.push(socket)
socket.close$.subscribe(() => {
this.sockets = this.sockets.filter(x => x !== socket)
})
return socket
}
async chooseConnectionGateway (): Promise<Gateway> {
try {
return await this.http.post('/api/1/gateways/choose', {}).toPromise()
} catch (err){
if (err.status === 503) {
throw new Error('All connections gateway are unavailable right now')
}
throw err
}
}
}

View File

@@ -0,0 +1,23 @@
import { Injectable } from '@angular/core'
@Injectable({ providedIn: 'root' })
export class CommonService {
private configPromise: Promise<any>
backendURL$: Promise<string>
constructor () {
this.configPromise = this.getConfig()
this.backendURL$ = this.configPromise.then(cfg => {
let backendURL = cfg.backendURL
if (backendURL.endsWith('/')) {
backendURL = backendURL.slice(0, -1)
}
return backendURL
})
}
private async getConfig () {
return (await fetch('/config.json')).json()
}
}

View File

@@ -0,0 +1,96 @@
import * as semverCompare from 'semver/functions/compare-loose'
import { AsyncSubject, Subject } from 'rxjs'
import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { Config, User, Version } from '../api'
import { LoginService } from './login.service'
@Injectable({ providedIn: 'root' })
export class ConfigService {
activeConfig$ = new Subject<Config>()
activeVersion$ = new Subject<Version>()
user: User
configs: Config[] = []
versions: Version[] = []
ready$ = new AsyncSubject<void>()
get activeConfig (): Config { return this._activeConfig }
get activeVersion (): Version { return this._activeVersion }
private _activeConfig: Config|null = null
private _activeVersion: Version|null = null
constructor (
private http: HttpClient,
private loginService: LoginService,
) {
this.init()
}
async updateUser () {
await this.http.put('/api/1/user', this.user).toPromise()
}
async createNewConfig (): Promise<Config> {
const config = await this.http.post('/api/1/configs', {
content: '{}',
last_used_with_version: this._activeVersion?.version ?? this.getLatestStableVersion().version,
}).toPromise()
this.configs.push(config)
return config
}
getLatestStableVersion () {
return this.versions[0]
}
async duplicateActiveConfig () {
const copy = {...this._activeConfig, pk: undefined}
this.configs.push(await this.http.post('/api/1/configs', copy).toPromise())
}
async selectVersion (version: Version) {
this._activeVersion = version
this.activeVersion$.next(version)
}
async selectConfig (config: Config) {
let matchingVersion = this.versions.find(x => x.version === config.last_used_with_version)
if (!matchingVersion) {
// TODO ask to upgrade
matchingVersion = this.versions[0]
}
this._activeConfig = config
this.activeConfig$.next(config)
this.selectVersion(matchingVersion)
this.loginService.user.active_config = config.id
await this.loginService.updateUser()
}
async selectDefaultConfig () {
await this.ready$.toPromise()
await this.loginService.ready$.toPromise()
this.selectConfig(this.configs.find(c => c.id === this.loginService.user.active_config) ?? this.configs[0])
}
async deleteConfig (config: Config) {
await this.http.delete(`/api/1/configs/${config.id}`).toPromise()
this.configs = this.configs.filter(x => x.id !== config.id)
}
private async init () {
this.configs = await this.http.get('/api/1/configs').toPromise()
this.versions = await this.http.get('/api/1/versions').toPromise()
this.versions.sort((a, b) => -semverCompare(a.version, b.version))
if (!this.configs.length) {
await this.createNewConfig()
}
this.ready$.next()
this.ready$.complete()
}
}

View File

@@ -0,0 +1,30 @@
import { AsyncSubject } from 'rxjs'
import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { User } from '../api'
@Injectable({ providedIn: 'root' })
export class LoginService {
user: User
ready$ = new AsyncSubject<void>()
constructor (private http: HttpClient) {
this.init()
}
async updateUser () {
await this.http.put('/api/1/user', this.user).toPromise()
}
private async init () {
try {
this.user = await this.http.get('/api/1/user').toPromise()
} catch {
this.user = null
}
this.ready$.next()
this.ready$.complete()
}
}