This commit is contained in:
Eugene Pankov
2021-10-31 18:15:23 +01:00
commit f677febac3
134 changed files with 11509 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
.modal-header
h5.modal-title Config file
.modal-body
.header(*ngIf='configService.activeConfig')
.d-flex.align-items-center.py-2
.me-auto
label Active config
.title
fa-icon([icon]='_configIcon')
span.ms-2 {{configService.activeConfig.name}}
button.btn.btn-semi.me-2((click)='configService.duplicateActiveConfig()')
fa-icon([icon]='_copyIcon', [fixedWidth]='true')
button.btn.btn-semi((click)='deleteConfig()')
fa-icon([icon]='_deleteIcon', [fixedWidth]='true')
.d-flex.align-items-center.py-2(*ngIf='configService.activeVersion')
.me-auto App version:
div(ngbDropdown)
button.btn.btn-semi(ngbDropdownToggle) {{configService.activeVersion.version}}
div(ngbDropdownMenu)
button(
*ngFor='let version of configService.versions',
ngbDropdownItem,
[class.active]='version == configService.activeVersion',
(click)='selectVersion(version)'
) {{version.version}}
.pt-3(*ngIf='configService.configs.length > 1')
h5 Other configs
.list-group.list-group-light
ng-container(*ngFor='let config of configService.configs')
button.list-group-item.list-group-item-action(
*ngIf='config.id !== configService.activeConfig?.id',
(click)='selectConfig(config)'
)
fa-icon([icon]='_configIcon')
span {{config.name}}
.py-3
button.btn.btn-semi.w-100((click)='createNewConfig()')
fa-icon([icon]='_addIcon', [fixedWidth]='true')
span New config

View File

@@ -0,0 +1,56 @@
import { Component } from '@angular/core'
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
import { AppConnectorService } from '../services/appConnector.service'
import { ConfigService } from 'src/common'
import { faCopy, faFile, faPlus, faTrash } from '@fortawesome/free-solid-svg-icons'
import { Config, Version } from 'src/api'
@Component({
selector: 'config-modal',
templateUrl: './configModal.component.pug',
// styleUrls: ['./settingsModal.component.scss'],
})
export class ConfigModalComponent {
_addIcon = faPlus
_copyIcon = faCopy
_deleteIcon = faTrash
_configIcon = faFile
constructor (
private modalInstance: NgbActiveModal,
public appConnector: AppConnectorService,
public configService: ConfigService,
) {
}
cancel () {
this.modalInstance.dismiss()
}
async createNewConfig () {
const config = await this.configService.createNewConfig()
await this.configService.selectConfig(config)
this.modalInstance.dismiss()
}
async selectConfig (config: Config) {
await this.configService.selectConfig(config)
this.modalInstance.dismiss()
}
async selectVersion (version: Version) {
await this.configService.selectVersion(version)
this.modalInstance.dismiss()
}
async deleteConfig () {
if (!this.configService.activeConfig) {
return
}
if (confirm('Delete this config? This cannot be undone.')) {
await this.configService.deleteConfig(this.configService.activeConfig)
}
this.configService.selectDefaultConfig()
this.modalInstance.dismiss()
}
}

View File

@@ -0,0 +1,8 @@
.list-group.list-group-light
.list-group-item.d-flex(*ngFor='let socket of appConnector.sockets')
fa-icon.text-success.me-2([icon]='_circleIcon', [fixedWidth]='true')
.me-auto
div {{socket.options.host}}:{{socket.options.port}}
.text-muted via {{socket.url}}
button.btn.btn-link((click)='closeSocket(socket)')
fa-icon([icon]='_closeIcon', [fixedWidth]='true')

View File

@@ -0,0 +1,20 @@
import { Component } from '@angular/core'
import { AppConnectorService, SocketProxy } from '../services/appConnector.service'
import { faCircle, faTimes } from '@fortawesome/free-solid-svg-icons'
@Component({
selector: 'connection-list',
templateUrl: './connectionList.component.pug',
})
export class ConnectionListComponent {
_circleIcon = faCircle
_closeIcon = faTimes
constructor (
public appConnector: AppConnectorService,
) { }
closeSocket (socket: SocketProxy) {
socket.close(new Error('Connection closed by user'))
}
}

View File

@@ -0,0 +1,36 @@
.sidebar
img.logo(src='{{_logo}}')
button.btn.mt-auto(
(click)='openConfig()',
title='Manage configs'
)
fa-icon([icon]='_configIcon', [fixedWidth]='true', size='lg')
button.btn(
(click)='openSettings()',
*ngIf='loginService.user',
title='Settings'
)
fa-icon([icon]='_settingsIcon', [fixedWidth]='true', size='lg')
a.btn.mt-3(
href='/login',
*ngIf='!loginService.user',
title='Log in'
)
fa-icon([icon]='_loginIcon', [fixedWidth]='true', size='lg')
button.btn.mt-3(
(click)='logout()',
*ngIf='loginService.user',
title='Log out'
)
fa-icon([icon]='_logoutIcon', [fixedWidth]='true', size='lg')
.terminal
iframe(#iframe, [hidden]='!showApp')
.alert.alert-warning.d-flex.border-0.m-0(*ngIf='showApp && !loginService.user')
fa-icon.me-2([icon]='_saveIcon', [fixedWidth]='true')
div
div To save profiles and settings, #[a(href='/login') log in].

View File

@@ -0,0 +1,66 @@
@import "~theme/vars";
:host {
position: absolute;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
display: flex;
}
.sidebar {
width: 64px;
flex: none;
display: flex;
flex-direction: column;
align-items: stretch;
.logo {
width: 32px;
height: 32px;
align-self: center;
margin-top: 15px;
margin-bottom: 20px;
}
>.btn {
width: 64px;
height: 64px;
background: transparent;
box-shadow: none;
&::after {
display: none;
}
&:hover {
color: white;
}
}
}
.terminal {
flex: 1 1 0;
overflow: hidden;
position: relative;
display: flex;
flex-direction: column;
> * {
flex: none;
}
> iframe {
background: $body-bg;
border: none;
flex: 1 1 0;
}
}
.config-menu {
.header {
border-bottom: 1px solid black;
}
}

View File

@@ -0,0 +1,104 @@
import { Component, ElementRef, ViewChild } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Title } from '@angular/platform-browser'
import { AppConnectorService } from '../services/appConnector.service'
import { faCog, faFile, faPlus, faSave, faSignInAlt, faSignOutAlt } from '@fortawesome/free-solid-svg-icons'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { SettingsModalComponent } from './settingsModal.component'
import { ConfigModalComponent } from './configModal.component'
import { ConfigService, LoginService } from 'src/common'
import { combineLatest } from 'rxjs'
import { Config, Version } from 'src/api'
@Component({
selector: 'main',
templateUrl: './main.component.pug',
styleUrls: ['./main.component.scss'],
})
export class MainComponent {
_logo = require('../../../assets/logo.svg')
_settingsIcon = faCog
_loginIcon = faSignInAlt
_logoutIcon = faSignOutAlt
_addIcon = faPlus
_configIcon = faFile
_saveIcon = faSave
showApp = false
@ViewChild('iframe') iframe: ElementRef
constructor (
titleService: Title,
public appConnector: AppConnectorService,
private http: HttpClient,
public loginService: LoginService,
private ngbModal: NgbModal,
private config: ConfigService,
) {
titleService.setTitle('Tabby')
window.addEventListener('message', this.connectorRequestHandler)
}
connectorRequestHandler = event => {
if (event.data === 'request-connector') {
this.iframe.nativeElement.contentWindow['__connector__'] = this.appConnector
this.iframe.nativeElement.contentWindow.postMessage('connector-ready', '*')
}
}
async ngAfterViewInit () {
await this.loginService.ready$.toPromise()
combineLatest(
this.config.activeConfig$,
this.config.activeVersion$
).subscribe(([config, version]) => {
this.reloadApp(config, version)
})
await this.config.ready$.toPromise()
await this.config.selectDefaultConfig()
}
ngOnDestroy () {
window.removeEventListener('message', this.connectorRequestHandler)
}
unloadApp () {
this.showApp = false
this.iframe.nativeElement.src = 'about:blank'
}
async loadApp (config, version) {
this.showApp = true
this.iframe.nativeElement.src = '/terminal'
if (this.loginService.user) {
await this.http.patch(`/api/1/configs/${config.id}`, {
last_used_with_version: version.version,
}).toPromise()
}
}
reloadApp (config: Config, version: Version) {
// TODO check config incompatibility
setTimeout(() => {
this.appConnector.setState(config, version)
this.loadApp(config, version)
})
}
async openConfig () {
await this.ngbModal.open(ConfigModalComponent).result
}
async openSettings () {
await this.ngbModal.open(SettingsModalComponent).result
}
async logout () {
await this.http.post('/api/1/auth/logout', null).toPromise()
location.href = '/'
}
}

View File

@@ -0,0 +1,72 @@
.modal-header
h3.modal-title Settings
.modal-body
.mb-3
h5 GitHub account
a.btn.btn-info(href='{{commonService.backendURL}}/api/1/auth/social/login/github', *ngIf='!user.github_username')
fa-icon([icon]='_githubIcon', [fixedWidth]='true')
span Connect a GitHub account
.alert.alert-success.d-flex(*ngIf='user.github_username')
fa-icon.me-2([icon]='_okIcon', [fixedWidth]='true')
div
div Connected as #[strong {{user.github_username}}]
div(*ngIf='user.is_sponsor') Thank you for supporting Tabby on GitHub!
.mb-3.mt-4
h5 Config sync
.d-flex.aling-items-stretch.mb-3
.form-floating.w-100
input.form-control(
type='text',
readonly,
[ngModel]='user.config_sync_token'
)
label Sync token for the Tabby app
button.btn.btn-dark([cdkCopyToClipboard]='user.config_sync_token')
fa-icon([icon]='_copyIcon', [fixedWidth]='true')
.mb-3.mt-4
h5 Connection gateway
.form-check.form-switch
input.form-check-input(
type='checkbox',
[(ngModel)]='customGatewayEnabled'
)
label(class='form-check-label') Use custom connection gateway
small.text-muted This allows you to securely route connections through your own hosted gateway. See #[a(href='https://github.com/Eugeny/tabby-connection-gateway#readme', target='_blank') tabby-connection-gateway] for setup instructions.
form
input.d-none(type='text', name='fakeusername')
input.d-none(type='password', name='fakepassword')
.mb-3(*ngIf='customGatewayEnabled')
.form-floating
input.form-control(
type='text',
[(ngModel)]='user.custom_connection_gateway',
placeholder='wss://1.2.3.4',
autocomplete='off'
)
label Gateway address
.mb-3(*ngIf='customGatewayEnabled')
.form-floating
input.form-control(
type='password',
[(ngModel)]='user.custom_connection_gateway_token',
placeholder='123',
autocomplete='new-password'
)
label Gateway authentication token
.mb-3.mt-4(*ngIf='appConnector.sockets.length')
h5 Active connections
connection-list
.modal-footer
.text-muted Account ID: {{user.id}}
.ms-auto
button.btn.btn-primary((click)='apply()') Apply
button.btn.btn-secondary((click)='cancel()') Cancel

View File

@@ -0,0 +1,42 @@
import { Component } from '@angular/core'
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
import { User } from 'src/api'
import { CommonService, LoginService } from 'src/common'
import { AppConnectorService } from '../services/appConnector.service'
import { faGithub } from '@fortawesome/free-brands-svg-icons'
import { faCheck, faCopy } from '@fortawesome/free-solid-svg-icons'
@Component({
selector: 'settings-modal',
templateUrl: './settingsModal.component.pug',
})
export class SettingsModalComponent {
user: User
customGatewayEnabled = false
_githubIcon = faGithub
_copyIcon = faCopy
_okIcon = faCheck
constructor (
public appConnector: AppConnectorService,
public commonService: CommonService,
private modalInstance: NgbActiveModal,
private loginService: LoginService,
) {
if (!loginService.user) {
return
}
this.user = { ...loginService.user }
this.customGatewayEnabled = !!this.user.custom_connection_gateway
}
async apply () {
Object.assign(this.loginService.user, this.user)
this.modalInstance.close()
await this.loginService.updateUser()
}
cancel () {
this.modalInstance.dismiss()
}
}

View File

@@ -0,0 +1,28 @@
.modal-header
h1.modal-title Hey!
.modal-body
h4 It looks like you're enjoying Tabby a lot!
p Tabby Web has a limit of {{appConnector.connectionLimit}} simultaneous connections due to the fact that I have to pay for hosting and traffic out of my own pocket.
p #[strong You can have unlimited parallel connections] if you support Tabby on GitHub with #[code $3]/month or more. It's cancellable anytime, there are no hidden costs and it helps me pay my bills.
a.btn.btn-primary.btn-lg.d-block.mb-3(href='https://github.com/sponsors/Eugeny', target='_blank')
fa-icon.me-2([icon]='_loveIcon')
span Support Tabby on GitHub
button.btn.btn-warning.d-block.w-100((click)='skipOnce()', *ngIf='canSkip')
fa-icon.me-2([icon]='_giftIcon')
span Skip - just this one time
p.mt-3 If you work in education, have already supported me on Ko-fi before, or your country isn't supported on GitHub Sponsors, just #[a(href='mailto:e@ajenti.org?subject=Help with Tabby Pro') let me know] and I'll hook you up.
.mb-3(*ngIf='!loginService.user?.github_username')
a.btn.btn-info(href='{{commonService.backendURL}}/api/1/auth/social/login/github')
fa-icon([icon]='_githubIcon', [fixedWidth]='true')
span Connect your GitHub account to link your sponsorship
.mt-4
p You can also kill any active connection from the list below to free up a slot.
connection-list

View File

@@ -0,0 +1,35 @@
import { Component } from '@angular/core'
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
import { faGithub } from '@fortawesome/free-brands-svg-icons'
import { faGift, faHeart } from '@fortawesome/free-solid-svg-icons'
import { AppConnectorService } from '../services/appConnector.service'
import { CommonService, LoginService } from 'src/common'
import { User } from 'src/api'
@Component({
selector: 'upgrade-modal',
templateUrl: './upgradeModal.component.pug',
})
export class UpgradeModalComponent {
user: User
_githubIcon = faGithub
_loveIcon = faHeart
_giftIcon = faGift
canSkip = false
constructor (
public appConnector: AppConnectorService,
public commonService: CommonService,
public loginService: LoginService,
private modalInstance: NgbActiveModal,
) {
this.canSkip = !window.localStorage['upgrade-modal-skipped']
}
skipOnce () {
window.localStorage['upgrade-modal-skipped'] = true
window.sessionStorage['upgrade-skip-active'] = true
this.modalInstance.close(true)
}
}

48
frontend/src/app/index.ts Normal file
View File

@@ -0,0 +1,48 @@
/* eslint-disable @typescript-eslint/no-extraneous-class */
import { NgModule } from '@angular/core'
import { NgbDropdownModule, NgbModalModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'
import { CommonModule } from '@angular/common'
import { FormsModule } from '@angular/forms'
import { RouterModule } from '@angular/router'
import { ClipboardModule } from '@angular/cdk/clipboard'
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'
import { MainComponent } from './components/main.component'
import { ConfigModalComponent } from './components/configModal.component'
import { SettingsModalComponent } from './components/settingsModal.component'
import { ConnectionListComponent } from './components/connectionList.component'
import { UpgradeModalComponent } from './components/upgradeModal.component'
import { InstanceInfoResolver } from 'src/api'
import { CommonAppModule } from 'src/common'
const ROUTES = [
{
path: '',
component: MainComponent,
resolve: {
instanceInfo: InstanceInfoResolver,
},
},
]
@NgModule({
imports: [
CommonAppModule,
CommonModule,
FormsModule,
NgbDropdownModule,
NgbModalModule,
NgbTooltipModule,
ClipboardModule,
FontAwesomeModule,
RouterModule.forChild(ROUTES),
],
declarations: [
MainComponent,
ConfigModalComponent,
SettingsModalComponent,
ConnectionListComponent,
UpgradeModalComponent,
],
})
export class ApplicationModule { }

View File

@@ -0,0 +1,233 @@
import { Buffer } from 'buffer'
import { Subject } from 'rxjs'
import { debounceTime } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
import { Injectable, Injector, NgZone } from '@angular/core'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { UpgradeModalComponent } from '../components/upgradeModal.component'
import { Config, Gateway, Version } from 'src/api'
import { LoginService, CommonService } from 'src/common'
export interface ServiceMessage {
_: string
[k: string]: any
}
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
private ngbModal: NgbModal
private zone: NgZone
constructor (
injector: Injector,
) {
this.appConnector = injector.get(AppConnectorService)
this.loginService = injector.get(LoginService)
this.ngbModal = injector.get(NgbModal)
this.zone = injector.get(NgZone)
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
async connect (options: any): Promise<void> {
if (!this.loginService.user?.is_pro && this.appConnector.sockets.length > this.appConnector.connectionLimit && !window.sessionStorage['upgrade-skip-active']) {
let skipped = false
try {
skipped = await this.zone.run(() => this.ngbModal.open(UpgradeModalComponent)).result
} catch { }
if (!skipped) {
this.close(new Error('Connection limit reached'))
return
}
}
this.options = options
if (this.loginService.user?.custom_connection_gateway) {
this.url = this.loginService.user.custom_connection_gateway
}
if (this.loginService.user?.custom_connection_gateway_token) {
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 = () => {
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: ServiceMessage): void {
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: ServiceMessage): void {
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
connectionLimit = 3
sockets: SocketProxy[] = []
constructor (
private injector: Injector,
private http: HttpClient,
private commonService: CommonService,
private zone: NgZone,
private loginService: LoginService,
) {
this.configUpdate.pipe(debounceTime(1000)).subscribe(async content => {
if (this.loginService.user) {
const result = await this.http.patch(`/api/1/configs/${this.config.id}`, { content }).toPromise()
Object.assign(this.config, result)
}
})
}
setState (config: Config, version: Version): void {
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
}
getDistURL (): string {
return 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 (): SocketProxy {
return this.zone.run(() => {
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() as Gateway
} catch (err){
if (err.status === 503) {
throw new Error('All connection gateways are unavailable right now')
}
throw err
}
}
}