dont watch patch.data directly in TS (#371)

* dont watch patch.data directly in TS

* installs and uninstalls working

* minor repairs
This commit is contained in:
Matt Hill
2021-07-20 10:20:39 -06:00
committed by Aiden McClelland
parent 65c4db09f3
commit d1b8f51b78
50 changed files with 444 additions and 340 deletions

View File

@@ -58,7 +58,6 @@
<ion-icon name="close"></ion-icon> <ion-icon name="close"></ion-icon>
<ion-icon name="close-outline"></ion-icon> <ion-icon name="close-outline"></ion-icon>
<ion-icon name="code-outline"></ion-icon> <ion-icon name="code-outline"></ion-icon>
<ion-icon name="cog-outline"></ion-icon>
<ion-icon name="color-wand-outline"></ion-icon> <ion-icon name="color-wand-outline"></ion-icon>
<ion-icon name="construct-outline"></ion-icon> <ion-icon name="construct-outline"></ion-icon>
<ion-icon name="copy-outline"></ion-icon> <ion-icon name="copy-outline"></ion-icon>
@@ -89,6 +88,7 @@
<ion-icon name="reload-outline"></ion-icon> <ion-icon name="reload-outline"></ion-icon>
<ion-icon name="remove-outline"></ion-icon> <ion-icon name="remove-outline"></ion-icon>
<ion-icon name="save-outline"></ion-icon> <ion-icon name="save-outline"></ion-icon>
<ion-icon name="shield-checkmark-outline"></ion-icon>
<ion-icon name="sync-circle-outline"></ion-icon> <ion-icon name="sync-circle-outline"></ion-icon>
<ion-icon name="storefront-outline"></ion-icon> <ion-icon name="storefront-outline"></ion-icon>
<ion-icon name="terminal-outline"></ion-icon> <ion-icon name="terminal-outline"></ion-icon>

View File

@@ -16,6 +16,7 @@ import { ConnectionFailure, ConnectionService } from './services/connection.serv
import { StartupAlertsService } from './services/startup-alerts.service' import { StartupAlertsService } from './services/startup-alerts.service'
import { ConfigService } from './services/config.service' import { ConfigService } from './services/config.service'
import { isEmptyObject } from './util/misc.util' import { isEmptyObject } from './util/misc.util'
import { MarketplaceApiService } from './services/api/marketplace/marketplace-api.service'
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
@@ -56,12 +57,13 @@ export class AppComponent {
private readonly storage: Storage, private readonly storage: Storage,
private readonly authService: AuthService, private readonly authService: AuthService,
private readonly router: Router, private readonly router: Router,
private readonly api: ApiService, private readonly embassyApi: ApiService,
private readonly http: HttpService, private readonly http: HttpService,
private readonly alertCtrl: AlertController, private readonly alertCtrl: AlertController,
private readonly loader: LoaderService, private readonly loader: LoaderService,
private readonly emver: Emver, private readonly emver: Emver,
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
private readonly marketplaceApi: MarketplaceApiService,
private readonly startupAlertsService: StartupAlertsService, private readonly startupAlertsService: StartupAlertsService,
private readonly toastCtrl: ToastController, private readonly toastCtrl: ToastController,
private readonly patch: PatchDbService, private readonly patch: PatchDbService,
@@ -95,26 +97,30 @@ export class AppComponent {
) )
.subscribe(_ => { .subscribe(_ => {
this.showMenu = true this.showMenu = true
this.router.navigate([''], { replaceUrl: true }) // if on the login screen, route to dashboard
this.connectionService.start() if (this.router.url.startsWith('/login')) {
this.router.navigate([''], { replaceUrl: true })
}
// start the connection monitor
this.connectionService.start(auth)
// watch connection to display connectivity issues
this.marketplaceApi.init(auth)
// watch connection to display connectivity issues // watch connection to display connectivity issues
this.watchConnection(auth) this.watchConnection(auth)
// watch router to highlight selected menu item // // watch router to highlight selected menu item
this.watchRouter(auth) this.watchRouter(auth)
// watch status to display/hide maintenance page // // watch status to display/hide maintenance page
this.watchStatus(auth) this.watchStatus(auth)
// watch version to refresh browser window // // watch version to refresh browser window
this.watchVersion(auth) this.watchVersion(auth)
// watch unread notification count to display toast // // watch unread notification count to display toast
this.watchNotifications(auth) this.watchNotifications(auth)
// run startup alerts // // run startup alerts
this.startupAlertsService.runChecks() this.startupAlertsService.runChecks()
}) })
// UNVERIFIED // UNVERIFIED
} else if (auth === AuthState.UNVERIFIED) { } else if (auth === AuthState.UNVERIFIED) {
this.showMenu = false this.showMenu = false
this.connectionService.stop()
this.patch.stop() this.patch.stop()
this.storage.clear() this.storage.clear()
this.router.navigate(['/login'], { replaceUrl: true }) this.router.navigate(['/login'], { replaceUrl: true })
@@ -220,7 +226,6 @@ export class AppComponent {
this.patch.watch$('server-info', 'unread-notification-count') this.patch.watch$('server-info', 'unread-notification-count')
.pipe( .pipe(
takeWhile(() => auth === AuthState.VERIFIED), takeWhile(() => auth === AuthState.VERIFIED),
finalize(() => console.log('FINALIZING!!!')),
) )
.subscribe(count => { .subscribe(count => {
this.unreadCount = count this.unreadCount = count
@@ -271,7 +276,7 @@ export class AppComponent {
private async logout () { private async logout () {
this.loader.of(LoadingSpinner('Logging out...')) this.loader.of(LoadingSpinner('Logging out...'))
.displayDuringP(this.api.logout({ })) .displayDuringP(this.embassyApi.logout({ }))
.then(() => this.authService.setUnverified()) .then(() => this.authService.setUnverified())
.catch(e => this.setError(e)) .catch(e => this.setError(e))
} }

View File

@@ -8,7 +8,7 @@ import { InstallWizardComponent, SlideDefinition, TopbarParams } from './install
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class WizardBaker { export class WizardBaker {
constructor ( constructor (
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
) { } ) { }
install (values: { install (values: {
@@ -43,7 +43,7 @@ export class WizardBaker {
action, action,
verb: 'beginning installation for', verb: 'beginning installation for',
title, title,
executeAction: () => this.apiService.installPackage({ id, version }), executeAction: () => this.embassyApi.installPackage({ id, version }),
}, },
}, },
bottomBar: { bottomBar: {
@@ -89,7 +89,7 @@ export class WizardBaker {
action, action,
verb: 'updating', verb: 'updating',
title, title,
fetchBreakages: () => this.apiService.dryUpdatePackage({ id, version }).then(breakages => breakages), fetchBreakages: () => this.embassyApi.dryUpdatePackage({ id, version }).then(breakages => breakages),
}, },
}, },
bottomBar: { bottomBar: {
@@ -104,7 +104,7 @@ export class WizardBaker {
action, action,
verb: 'beginning update for', verb: 'beginning update for',
title, title,
executeAction: () => this.apiService.installPackage({ id, version }), executeAction: () => this.embassyApi.installPackage({ id, version }),
}, },
}, },
bottomBar: { bottomBar: {
@@ -149,7 +149,7 @@ export class WizardBaker {
action, action,
verb: 'beginning update for', verb: 'beginning update for',
title, title,
executeAction: () => this.apiService.updateServer({ }), executeAction: () => this.embassyApi.updateServer({ }),
}, },
}, },
bottomBar: { bottomBar: {
@@ -191,7 +191,7 @@ export class WizardBaker {
action, action,
verb: 'downgrading', verb: 'downgrading',
title, title,
fetchBreakages: () => this.apiService.dryUpdatePackage({ id, version }).then(breakages => breakages), fetchBreakages: () => this.embassyApi.dryUpdatePackage({ id, version }).then(breakages => breakages),
}, },
}, },
bottomBar: { bottomBar: {
@@ -204,7 +204,7 @@ export class WizardBaker {
action, action,
verb: 'beginning downgrade for', verb: 'beginning downgrade for',
title, title,
executeAction: () => this.apiService.installPackage({ id, version }), executeAction: () => this.embassyApi.installPackage({ id, version }),
}, },
}, },
bottomBar: { bottomBar: {
@@ -246,7 +246,7 @@ export class WizardBaker {
action, action,
verb: 'uninstalling', verb: 'uninstalling',
title, title,
fetchBreakages: () => this.apiService.dryRemovePackage({ id }).then(breakages => breakages), fetchBreakages: () => this.embassyApi.dryRemovePackage({ id }).then(breakages => breakages),
}, },
}, },
bottomBar: { cancel: { whileLoading: { }, afterLoading: { text: 'Cancel' } }, next: 'Uninstall' }, bottomBar: { cancel: { whileLoading: { }, afterLoading: { text: 'Cancel' } }, next: 'Uninstall' },
@@ -258,7 +258,7 @@ export class WizardBaker {
action, action,
verb: 'uninstalling', verb: 'uninstalling',
title, title,
executeAction: () => this.apiService.removePackage({ id }), executeAction: () => this.embassyApi.removePackage({ id }),
}, },
}, },
bottomBar: { finish: 'Dismiss', cancel: { whileLoading: { } } }, bottomBar: { finish: 'Dismiss', cancel: { whileLoading: { } } },

View File

@@ -7,6 +7,7 @@ import { PatchDbService } from '../services/patch-db/patch-db.service'
providedIn: 'root', providedIn: 'root',
}) })
export class MaintenanceGuard implements CanActivate, CanActivateChild { export class MaintenanceGuard implements CanActivate, CanActivateChild {
constructor ( constructor (
private readonly router: Router, private readonly router: Router,
private readonly patch: PatchDbService, private readonly patch: PatchDbService,

View File

@@ -17,12 +17,12 @@ export class MarkdownPage {
constructor ( constructor (
private readonly modalCtrl: ModalController, private readonly modalCtrl: ModalController,
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
) { } ) { }
async ngOnInit () { async ngOnInit () {
try { try {
this.content = await this.apiService.getStatic(this.contentUrl) this.content = await this.embassyApi.getStatic(this.contentUrl)
} catch (e) { } catch (e) {
console.error(e.message) console.error(e.message)
this.errToast.present(e.message) this.errToast.present(e.message)

View File

@@ -13,12 +13,12 @@ export class OSWelcomePage {
constructor ( constructor (
private readonly modalCtrl: ModalController, private readonly modalCtrl: ModalController,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly config: ConfigService, private readonly config: ConfigService,
) { } ) { }
async dismiss () { async dismiss () {
this.apiService.setDbValue({ pointer: '/welcome-ack', value: this.config.version }) this.embassyApi.setDbValue({ pointer: '/welcome-ack', value: this.config.version })
.catch(console.error) .catch(console.error)
// return false to skip subsequent alert modals (e.g. check for updates modals) // return false to skip subsequent alert modals (e.g. check for updates modals)

View File

@@ -8,7 +8,6 @@ import { TruncateCenterPipe, TruncateEndPipe } from '../pipes/truncate.pipe'
import { MaskPipe } from '../pipes/mask.pipe' import { MaskPipe } from '../pipes/mask.pipe'
import { HasUiPipe, LaunchablePipe } from '../pipes/ui.pipe' import { HasUiPipe, LaunchablePipe } from '../pipes/ui.pipe'
import { EmptyPipe } from '../pipes/empty.pipe' import { EmptyPipe } from '../pipes/empty.pipe'
import { StatusPipe } from '../pipes/status.pipe'
import { NotificationColorPipe } from '../pipes/notification-color.pipe' import { NotificationColorPipe } from '../pipes/notification-color.pipe'
@NgModule({ @NgModule({
@@ -26,7 +25,6 @@ import { NotificationColorPipe } from '../pipes/notification-color.pipe'
HasUiPipe, HasUiPipe,
LaunchablePipe, LaunchablePipe,
EmptyPipe, EmptyPipe,
StatusPipe,
NotificationColorPipe, NotificationColorPipe,
], ],
imports: [], imports: [],
@@ -44,7 +42,6 @@ import { NotificationColorPipe } from '../pipes/notification-color.pipe'
HasUiPipe, HasUiPipe,
LaunchablePipe, LaunchablePipe,
EmptyPipe, EmptyPipe,
StatusPipe,
NotificationColorPipe, NotificationColorPipe,
], ],
}) })

View File

@@ -26,7 +26,7 @@ export class AppActionsPage {
constructor ( constructor (
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly modalCtrl: ModalController, private readonly modalCtrl: ModalController,
private readonly alertCtrl: AlertController, private readonly alertCtrl: AlertController,
private readonly loaderService: LoaderService, private readonly loaderService: LoaderService,
@@ -123,7 +123,7 @@ export class AppActionsPage {
private async executeAction (pkgId: string, actionId: string) { private async executeAction (pkgId: string, actionId: string) {
try { try {
const res = await this.loaderService.displayDuringP( const res = await this.loaderService.displayDuringP(
this.apiService.executePackageAction({ id: pkgId, 'action-id': actionId }), this.embassyApi.executePackageAction({ id: pkgId, 'action-id': actionId }),
) )
const successAlert = await this.alertCtrl.create({ const successAlert = await this.alertCtrl.create({

View File

@@ -50,7 +50,7 @@ export class AppConfigPage {
private readonly navCtrl: NavController, private readonly navCtrl: NavController,
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
private readonly wizardBaker: WizardBaker, private readonly wizardBaker: WizardBaker,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly loader: LoaderService, private readonly loader: LoaderService,
private readonly alertCtrl: AlertController, private readonly alertCtrl: AlertController,
private readonly modalController: ModalController, private readonly modalController: ModalController,
@@ -86,12 +86,12 @@ export class AppConfigPage {
.pipe( .pipe(
tap(pkg => this.pkg = pkg), tap(pkg => this.pkg = pkg),
tap(() => this.loadingText = 'Fetching config spec...'), tap(() => this.loadingText = 'Fetching config spec...'),
concatMap(() => this.apiService.getPackageConfig({ id: pkgId })), concatMap(() => this.embassyApi.getPackageConfig({ id: pkgId })),
concatMap(({ spec, config }) => { concatMap(({ spec, config }) => {
const rec = history.state && history.state.configRecommendation as Recommendation const rec = history.state && history.state.configRecommendation as Recommendation
if (rec) { if (rec) {
this.loadingText = `Setting properties to accommodate ${rec.dependentTitle}...` this.loadingText = `Setting properties to accommodate ${rec.dependentTitle}...`
return from(this.apiService.dryConfigureDependency({ 'dependency-id': pkgId, 'dependent-id': rec.dependentId })) return from(this.embassyApi.dryConfigureDependency({ 'dependency-id': pkgId, 'dependent-id': rec.dependentId }))
.pipe( .pipe(
map(res => ({ map(res => ({
spec, spec,
@@ -162,7 +162,7 @@ export class AppConfigPage {
spinner: 'lines', spinner: 'lines',
cssClass: 'loader', cssClass: 'loader',
}).displayDuringAsync(async () => { }).displayDuringAsync(async () => {
const breakages = await this.apiService.drySetPackageConfig({ id: pkg.manifest.id, config: this.config }) const breakages = await this.embassyApi.drySetPackageConfig({ id: pkg.manifest.id, config: this.config })
if (!isEmptyObject(breakages.length)) { if (!isEmptyObject(breakages.length)) {
const { cancelled } = await wizardModal( const { cancelled } = await wizardModal(
@@ -175,7 +175,7 @@ export class AppConfigPage {
if (cancelled) return { skip: true } if (cancelled) return { skip: true }
} }
return this.apiService.setPackageConfig({ id: pkg.manifest.id, config: this.config }) return this.embassyApi.setPackageConfig({ id: pkg.manifest.id, config: this.config })
.then(() => ({ skip: false })) .then(() => ({ skip: false }))
}) })
.then(({ skip }) => { .then(({ skip }) => {

View File

@@ -19,15 +19,17 @@ export class AppInstructionsPage {
constructor ( constructor (
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly patch: PatchDbService, private readonly patch: PatchDbService,
) { } ) { }
async ngOnInit () { async ngOnInit () {
const pkgId = this.route.snapshot.paramMap.get('pkgId') const pkgId = this.route.snapshot.paramMap.get('pkgId')
const url = this.patch.data['package-data'][pkgId]['static-files'].instructions const url = this.patch.data['package-data'][pkgId]['static-files'].instructions
try { try {
this.instructions = await this.apiService.getStatic(url) this.instructions = await this.embassyApi.getStatic(url)
} catch (e) { } catch (e) {
console.error(e) console.error(e)
this.errToast.present(e.message) this.errToast.present(e.message)
@@ -35,8 +37,4 @@ export class AppInstructionsPage {
this.loading = false this.loading = false
} }
} }
ngAfterViewInit () {
this.content.scrollToPoint(undefined, 1)
}
} }

View File

@@ -10,7 +10,7 @@
<ion-content> <ion-content>
<ion-grid *ngIf="patch.data['package-data'][pkgId] as pkg"> <ion-grid *ngIf="patch.data['package-data'][pkgId] as pkg">
<ion-row> <ion-row>
<ion-col *ngFor="let interface of pkg.manifest.interfaces | keyvalue: asIsOrder" sizeSm="12" sizeMd="6"> <ion-col *ngFor="let interface of pkg.manifest.interfaces | keyvalue: asIsOrder" sizeXs="12" sizeSm="12" sizeMd="6">
<ion-card> <ion-card>
<ion-card-header> <ion-card-header>
<ion-card-title>{{ interface.value.name }}</ion-card-title> <ion-card-title>{{ interface.value.name }}</ion-card-title>

View File

@@ -8,41 +8,40 @@
</ion-header> </ion-header>
<ion-content style="position: relative"> <ion-content style="position: relative">
<div *ngIf="patch.data['package-data'] as pkgs"> <div *ngIf="pkgs | empty; else list" class="ion-text-center ion-padding">
<div *ngIf="pkgs | empty; else list" class="ion-text-center ion-padding"> <div style="display: flex; flex-direction: column; justify-content: center; height: 40vh">
<div style="display: flex; flex-direction: column; justify-content: center; height: 40vh"> <h2>Welcome to your <span style="font-style: italic; color: var(--ion-color-danger)">Embassy</span></h2>
<h2>Welcome to your <span style="font-style: italic; color: var(--ion-color-danger)">Embassy</span></h2> <p class="ion-text-wrap">Get started by installing your first service.</p>
<p class="ion-text-wrap">Get started by installing your first service.</p>
</div>
<ion-button [routerLink]="['/marketplace']" style="width: 50%;" fill="outline">
<ion-icon slot="start" name="storefront-outline"></ion-icon>
Marketplace
</ion-button>
</div> </div>
<ion-button [routerLink]="['/marketplace']" style="width: 50%;" fill="outline">
<ng-template #list> <ion-icon slot="start" name="storefront-outline"></ion-icon>
<ion-grid> Marketplace
<ion-row> </ion-button>
<ion-col *ngFor="let pkg of pkgs | keyvalue : asIsOrder" sizeXs="4" sizeSm="3" sizeLg="3" sizeXl="2">
<ion-card class="installed-card" [routerLink]="['/services', pkg.value.manifest.id]">
<div class="launch-container" *ngIf="pkg.value | hasUi">
<div class="launch-button-triangle" (click)="launchUi(pkg.value, $event)" [class.launch-disabled]="!(pkg.value | isLaunchable)">
<ion-icon name="rocket-outline"></ion-icon>
</div>
</div>
<img style="position: absolute" class="main-img" [src]="pkg.value['static-files'].icon" alt="icon" />
<img class="main-img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=">
<img [class]="serviceInfo[pkg.key].bulbInfo.class" [src]="serviceInfo[pkg.key].bulbInfo.img"/>
<ion-card-header>
<status [rendering]="serviceInfo[pkg.key].rendering" size="calc(8px + .4vw)" weight="bold"></status>
<ion-card-title>{{ pkg.value.manifest.title }}</ion-card-title>
</ion-card-header>
</ion-card>
</ion-col>
</ion-row>
</ion-grid>
</ng-template>
</div> </div>
<ng-template #list>
<ion-grid>
<ion-row>
<ion-col *ngFor="let pkg of pkgs | keyvalue : asIsOrder" sizeXs="4" sizeSm="3" sizeLg="3" sizeXl="2">
<ion-card class="installed-card" [routerLink]="['/services', pkg.value.entry.manifest.id]">
<div class="launch-container" *ngIf="pkg.value.entry | hasUi">
<div class="launch-button-triangle" (click)="launchUi(pkg.value.entry, $event)" [class.launch-disabled]="!(pkg.value.entry | isLaunchable)">
<ion-icon name="rocket-outline"></ion-icon>
</div>
</div>
<img style="position: absolute" class="main-img" [src]="pkg.value.entry['static-files'].icon" alt="icon" />
<img class="main-img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=">
<img *ngIf="connectionFailure" class="bulb-off" src="assets/img/off-bulb.png" />
<img *ngIf="!connectionFailure" [class]="pkg.value.bulb.class" [src]="pkg.value.bulb.img" />
<ion-card-header>
<status [rendering]="pkg.value.statusRendering" size="calc(8px + .4vw)" weight="bold"></status>
<ion-card-title>{{ pkg.value.entry.manifest.title }}</ion-card-title>
</ion-card-header>
</ion-card>
</ion-col>
</ion-row>
</ion-grid>
</ng-template>
</ion-content> </ion-content>

View File

@@ -1,10 +1,11 @@
import { Component } from '@angular/core' import { Component } from '@angular/core'
import { ConfigService } from 'src/app/services/config.service' import { ConfigService } from 'src/app/services/config.service'
import { ConnectionService } from 'src/app/services/connection.service' import { ConnectionFailure, ConnectionService } from 'src/app/services/connection.service'
import { PatchDbService } from 'src/app/services/patch-db/patch-db.service' import { PatchDbService } from 'src/app/services/patch-db/patch-db.service'
import { PackageDataEntry } from 'src/app/services/patch-db/data-model' import { PackageDataEntry } from 'src/app/services/patch-db/data-model'
import { combineLatest, Subscription } from 'rxjs' import { Subscription } from 'rxjs'
import { PkgStatusRendering, renderPkgStatus } from 'src/app/services/pkg-status-rendering.service' import { PkgStatusRendering, renderPkgStatus } from 'src/app/services/pkg-status-rendering.service'
import { distinctUntilChanged, filter } from 'rxjs/operators'
@Component({ @Component({
selector: 'app-list', selector: 'app-list',
@@ -12,70 +13,94 @@ import { PkgStatusRendering, renderPkgStatus } from 'src/app/services/pkg-status
styleUrls: ['./app-list.page.scss'], styleUrls: ['./app-list.page.scss'],
}) })
export class AppListPage { export class AppListPage {
connected: boolean
subs: Subscription[] = [] subs: Subscription[] = []
serviceInfo: { [id: string]: { connectionFailure: boolean
bulbInfo: { pkgs: { [id: string]: {
entry: PackageDataEntry
bulb: {
class: string class: string
img: string img: string
} }
rendering: PkgStatusRendering statusRendering: PkgStatusRendering | null
sub: Subscription | null
}} = { } }} = { }
constructor ( constructor (
private readonly config: ConfigService, private readonly config: ConfigService,
public readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
public readonly patch: PatchDbService, public readonly patch: PatchDbService,
) { } ) { }
ngOnInit () { ngOnInit () {
this.subs = [ this.subs = [
combineLatest([ this.patch.watch$('package-data')
this.patch.connected$(), .pipe(
this.patch.watch$('package-data'), filter(obj => {
]) return Object.keys(obj).length !== Object.keys(this.pkgs).length
.subscribe(([connected, pkgs]) => { }),
this.connected = connected )
.subscribe(pkgs => {
const ids = Object.keys(pkgs)
console.log('PKGSPKGS', ids)
Object.keys(pkgs).forEach(pkgId => { Object.keys(this.pkgs).forEach(id => {
let bulbClass = 'bulb-on' if (!ids.includes(id)) {
let img = '' this.pkgs[id].sub.unsubscribe()
delete this.pkgs[id]
if (!this.connected) {
bulbClass = 'bulb-off',
img = 'assets/img/off-bulb.png'
}
const rendering = renderPkgStatus(pkgs[pkgId].state, pkgs[pkgId].installed.status)
switch (rendering.color) {
case 'danger':
img = 'assets/img/danger-bulb.png'
break
case 'success':
img = 'assets/img/success-bulb.png'
break
case 'warning':
img = 'assets/img/warning-bulb.png'
break
default:
bulbClass = 'bulb-off',
img = 'assets/img/off-bulb.png'
break
}
this.serviceInfo[pkgId] = {
bulbInfo: {
class: bulbClass,
img,
},
rendering,
} }
}) })
ids.forEach(id => {
// if already subscribed, return
if (this.pkgs[id]) return
this.pkgs[id] = {
entry: pkgs[id],
bulb: {
class: 'bulb-off',
img: 'assets/img/off-bulb.png',
},
statusRendering: renderPkgStatus(pkgs[id].state, pkgs[id].installed?.status),
sub: null,
}
// subscribe to pkg
this.pkgs[id].sub = this.patch.watch$('package-data', id).subscribe(pkg => {
let bulbClass = 'bulb-on'
let img = ''
const statusRendering = renderPkgStatus(pkgs[id].state, pkgs[id].installed?.status)
switch (statusRendering.color) {
case 'danger':
img = 'assets/img/danger-bulb.png'
break
case 'success':
img = 'assets/img/success-bulb.png'
break
case 'warning':
img = 'assets/img/warning-bulb.png'
break
default:
bulbClass = 'bulb-off',
img = 'assets/img/off-bulb.png'
break
}
this.pkgs[id].entry = pkg
this.pkgs[id].bulb = {
class: bulbClass,
img,
}
this.pkgs[id].statusRendering = statusRendering
})
})
}),
this.connectionService.watchFailure$()
.subscribe(connectionFailure => {
this.connectionFailure = connectionFailure !== ConnectionFailure.None
}), }),
] ]
} }
ngOnDestroy () { ngOnDestroy () {
Object.values(this.pkgs).forEach(pkg => pkg.sub.unsubscribe())
this.subs.forEach(sub => sub.unsubscribe()) this.subs.forEach(sub => sub.unsubscribe())
} }

View File

@@ -17,7 +17,7 @@ export class AppLogsPage {
constructor ( constructor (
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
) { } ) { }
ngOnInit () { ngOnInit () {
@@ -29,7 +29,7 @@ export class AppLogsPage {
this.logs = '' this.logs = ''
try { try {
const logs = await this.apiService.getPackageLogs({ id: this.pkgId }) const logs = await this.embassyApi.getPackageLogs({ id: this.pkgId })
this.logs = logs.map(l => `${l.timestamp} ${l.log}`).join('\n\n') this.logs = logs.map(l => `${l.timestamp} ${l.log}`).join('\n\n')
setTimeout(async () => await this.content.scrollToBottom(100), 200) setTimeout(async () => await this.content.scrollToBottom(100), 200)
} catch (e) { } catch (e) {

View File

@@ -3,7 +3,6 @@ import { ActivatedRoute } from '@angular/router'
import { Subscription } from 'rxjs' import { Subscription } from 'rxjs'
import { PackageDataEntry } from 'src/app/services/patch-db/data-model' import { PackageDataEntry } from 'src/app/services/patch-db/data-model'
import { PatchDbService } from 'src/app/services/patch-db/patch-db.service' import { PatchDbService } from 'src/app/services/patch-db/patch-db.service'
import { getManifest } from 'src/app/services/config.service'
import * as JsonPointer from 'json-pointer' import * as JsonPointer from 'json-pointer'
import { IonContent } from '@ionic/angular' import { IonContent } from '@ionic/angular'
@@ -56,7 +55,7 @@ export class AppManifestPage {
} }
private setNode () { private setNode () {
this.node = JsonPointer.get(getManifest(this.pkg), this.pointer || '') this.node = JsonPointer.get(this.pkg.manifest, this.pointer || '')
} }
async goToNested (key: string): Promise<any> { async goToNested (key: string): Promise<any> {

View File

@@ -9,7 +9,7 @@
<ion-content> <ion-content>
<ion-card> <ion-card *ngIf="mainStatus">
<ion-card-header> <ion-card-header>
<ion-card-title> <ion-card-title>
<ion-icon style="vertical-align: middle; padding-right: 12px;" name="medkit-outline"></ion-icon> <ion-icon style="vertical-align: middle; padding-right: 12px;" name="medkit-outline"></ion-icon>
@@ -17,15 +17,15 @@
</ion-card-title> </ion-card-title>
</ion-card-header> </ion-card-header>
<ion-card-content> <ion-card-content>
<ion-item *ngIf="pkg.installed?.status.main.health | empty; else health"> <ion-item *ngIf="mainStatus.health | empty; else health">
<ion-label> <ion-label>
No health checks No health checks
</ion-label> </ion-label>
</ion-item> </ion-item>
<ng-template #health> <ng-template #health>
<ion-item *ngIf="!(pkg.installed?.status.main.health | empty); else noHealth" color="light" style="margin: 10px;"> <ion-item *ngIf="!(mainStatus.health | empty); else noHealth" color="light" style="margin: 10px;">
<ion-label> <ion-label>
<div *ngFor="let health of pkg.installed.status.main.health | keyvalue : asIsOrder" class="align" style="margin-left: 12px;"> <div *ngFor="let health of mainStatus.health | keyvalue : asIsOrder" class="align" style="margin-left: 12px;">
<ion-icon *ngIf="health.value.result === 'success'" name="checkmark-outline" color="success"></ion-icon> <ion-icon *ngIf="health.value.result === 'success'" name="checkmark-outline" color="success"></ion-icon>
<ion-icon *ngIf="health.value.result === 'starting'" name="timer-outline" color="warning"></ion-icon> <ion-icon *ngIf="health.value.result === 'starting'" name="timer-outline" color="warning"></ion-icon>
<ion-icon *ngIf="health.value.result === 'loading'" name="sync-circle-outline" color="warning"></ion-icon> <ion-icon *ngIf="health.value.result === 'loading'" name="sync-circle-outline" color="warning"></ion-icon>

View File

@@ -1,10 +1,11 @@
import { Component, ViewChild } from '@angular/core' import { Component, ViewChild } from '@angular/core'
import { ActivatedRoute } from '@angular/router' import { ActivatedRoute } from '@angular/router'
import { IonContent } from '@ionic/angular' import { IonContent } from '@ionic/angular'
import { Subscription } from 'rxjs'
import { Metric } from 'src/app/services/api/api.types' import { Metric } from 'src/app/services/api/api.types'
import { ApiService } from 'src/app/services/api/embassy/embassy-api.service' import { ApiService } from 'src/app/services/api/embassy/embassy-api.service'
import { ErrorToastService } from 'src/app/services/error-toast.service' import { ErrorToastService } from 'src/app/services/error-toast.service'
import { PackageDataEntry } from 'src/app/services/patch-db/data-model' import { MainStatus } from 'src/app/services/patch-db/data-model'
import { PatchDbService } from 'src/app/services/patch-db/patch-db.service' import { PatchDbService } from 'src/app/services/patch-db/patch-db.service'
import { pauseFor } from 'src/app/util/misc.util' import { pauseFor } from 'src/app/util/misc.util'
@@ -16,9 +17,10 @@ import { pauseFor } from 'src/app/util/misc.util'
export class AppMetricsPage { export class AppMetricsPage {
loading = true loading = true
pkgId: string pkgId: string
pkg: PackageDataEntry mainStatus: MainStatus
going = false going = false
metrics: Metric metrics: Metric
subs: Subscription[] = []
@ViewChild(IonContent) content: IonContent @ViewChild(IonContent) content: IonContent
@@ -26,12 +28,17 @@ export class AppMetricsPage {
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly patch: PatchDbService, private readonly patch: PatchDbService,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
) { } ) { }
ngOnInit () { ngOnInit () {
this.pkgId = this.route.snapshot.paramMap.get('pkgId') this.pkgId = this.route.snapshot.paramMap.get('pkgId')
this.pkg = this.patch.data['package-data'][this.pkgId] this.subs = [
this.patch.watch$('package-data', this.pkgId, 'installed', 'status', 'main')
.subscribe(main => {
this.mainStatus = main
}),
]
this.startDaemon() this.startDaemon()
} }
@@ -42,6 +49,7 @@ export class AppMetricsPage {
ngOnDestroy () { ngOnDestroy () {
this.stopDaemon() this.stopDaemon()
this.subs.forEach(sub => sub.unsubscribe())
} }
async startDaemon (): Promise<void> { async startDaemon (): Promise<void> {
@@ -58,7 +66,7 @@ export class AppMetricsPage {
async getMetrics (): Promise<void> { async getMetrics (): Promise<void> {
try { try {
this.metrics = await this.apiService.getPkgMetrics({ id: this.pkgId}) this.metrics = await this.embassyApi.getPkgMetrics({ id: this.pkgId})
} catch (e) { } catch (e) {
console.error(e) console.error(e)
this.errToast.present(e.message) this.errToast.present(e.message)

View File

@@ -30,7 +30,7 @@ export class AppPropertiesPage {
constructor ( constructor (
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly alertCtrl: AlertController, private readonly alertCtrl: AlertController,
private readonly toastCtrl: ToastController, private readonly toastCtrl: ToastController,
@@ -41,16 +41,20 @@ export class AppPropertiesPage {
async ngOnInit () { async ngOnInit () {
this.pkgId = this.route.snapshot.paramMap.get('pkgId') this.pkgId = this.route.snapshot.paramMap.get('pkgId')
this.running = this.patch.data['package-data'][this.pkgId].installed?.status.main.status === PackageMainStatus.Running
await this.getProperties() await this.getProperties()
this.subs = [ this.subs = [
this.route.queryParams.subscribe(queryParams => { this.route.queryParams
.subscribe(queryParams => {
if (queryParams['pointer'] === this.pointer) return if (queryParams['pointer'] === this.pointer) return
this.pointer = queryParams['pointer'] this.pointer = queryParams['pointer']
this.node = JsonPointer.get(this.properties, this.pointer || '') this.node = JsonPointer.get(this.properties, this.pointer || '')
}), }),
this.patch.watch$('package-data', this.pkgId, 'installed', 'status', 'main', 'status')
.subscribe(status => {
this.running = status === PackageMainStatus.Running
}),
] ]
} }
@@ -115,7 +119,7 @@ export class AppPropertiesPage {
private async getProperties (): Promise<void> { private async getProperties (): Promise<void> {
this.loading = true this.loading = true
try { try {
this.properties = await this.apiService.getPackageProperties({ id: this.pkgId }) this.properties = await this.embassyApi.getPackageProperties({ id: this.pkgId })
this.node = JsonPointer.get(this.properties, this.pointer || '') this.node = JsonPointer.get(this.properties, this.pointer || '')
} catch (e) { } catch (e) {
console.error(e) console.error(e)

View File

@@ -21,7 +21,7 @@
<ion-label class="ion-text-wrap"> <ion-label class="ion-text-wrap">
<p class="ion-padding-bottom"><ion-text color="warning">Warning</ion-text></p> <p class="ion-padding-bottom"><ion-text color="warning">Warning</ion-text></p>
<h2> <h2>
Restoring from backup will overwrite all current data for {{ title }} . Restoring from backup will overwrite all current data for {{ patch.data['package-data'][pkgId].manifest.title }} .
</h2> </h2>
</ion-label> </ion-label>
</ion-item> </ion-item>

View File

@@ -6,6 +6,7 @@ import { DiskInfo } from 'src/app/services/api/api.types'
import { ActivatedRoute } from '@angular/router' import { ActivatedRoute } from '@angular/router'
import { PatchDbService } from 'src/app/services/patch-db/patch-db.service' import { PatchDbService } from 'src/app/services/patch-db/patch-db.service'
import { Subscription } from 'rxjs' import { Subscription } from 'rxjs'
import { take } from 'rxjs/operators'
@Component({ @Component({
selector: 'app-restore', selector: 'app-restore',
@@ -26,15 +27,13 @@ export class AppRestorePage {
constructor ( constructor (
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
private readonly modalCtrl: ModalController, private readonly modalCtrl: ModalController,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly loadingCtrl: LoadingController, private readonly loadingCtrl: LoadingController,
private readonly patch: PatchDbService, public readonly patch: PatchDbService,
) { } ) { }
ngOnInit () { ngOnInit () {
this.pkgId = this.route.snapshot.paramMap.get('pkgId') this.pkgId = this.route.snapshot.paramMap.get('pkgId')
this.title = this.patch.data['package-data'][this.pkgId].manifest.title
this.getExternalDisks() this.getExternalDisks()
} }
@@ -49,7 +48,7 @@ export class AppRestorePage {
async getExternalDisks (): Promise<void> { async getExternalDisks (): Promise<void> {
try { try {
this.disks = await this.apiService.getDisks({ }) this.disks = await this.embassyApi.getDisks({ })
this.allPartitionsMounted = Object.values(this.disks).every(d => Object.values(d.partitions).every(p => p['is-mounted'])) this.allPartitionsMounted = Object.values(this.disks).every(d => Object.values(d.partitions).every(p => p['is-mounted']))
} catch (e) { } catch (e) {
console.error(e) console.error(e)
@@ -87,7 +86,7 @@ export class AppRestorePage {
await loader.present() await loader.present()
try { try {
await this.apiService.restorePackage({ await this.embassyApi.restorePackage({
id: this.pkgId, id: this.pkgId,
logicalname, logicalname,
password, password,

View File

@@ -40,7 +40,7 @@ export class AppShowPage {
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly loader: LoaderService, private readonly loader: LoaderService,
private readonly modalCtrl: ModalController, private readonly modalCtrl: ModalController,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly wizardBaker: WizardBaker, private readonly wizardBaker: WizardBaker,
private readonly config: ConfigService, private readonly config: ConfigService,
public readonly patch: PatchDbService, public readonly patch: PatchDbService,
@@ -49,13 +49,13 @@ export class AppShowPage {
async ngOnInit () { async ngOnInit () {
this.pkgId = this.route.snapshot.paramMap.get('pkgId') this.pkgId = this.route.snapshot.paramMap.get('pkgId')
this.pkg = this.patch.data['package-data'][this.pkgId]
this.subs = [ this.subs = [
combineLatest([ combineLatest([
this.patch.connected$(), this.patch.connected$(),
this.patch.watch$('package-data', this.pkgId), this.patch.watch$('package-data', this.pkgId),
]) ])
.subscribe(([connected, pkg]) => { .subscribe(([connected, pkg]) => {
this.pkg = pkg
this.connected = connected this.connected = connected
this.rendering = renderPkgStatus(pkg.state, pkg.installed.status) this.rendering = renderPkgStatus(pkg.state, pkg.installed.status)
}), }),
@@ -82,7 +82,7 @@ export class AppShowPage {
spinner: 'lines', spinner: 'lines',
cssClass: 'loader', cssClass: 'loader',
}).displayDuringAsync(async () => { }).displayDuringAsync(async () => {
const breakages = await this.apiService.dryStopPackage({ id }) const breakages = await this.embassyApi.dryStopPackage({ id })
console.log('BREAKAGES', breakages) console.log('BREAKAGES', breakages)
@@ -100,7 +100,7 @@ export class AppShowPage {
if (cancelled) return { } if (cancelled) return { }
} }
return this.apiService.stopPackage({ id }).then(chill) return this.embassyApi.stopPackage({ id }).then(chill)
}).catch(e => this.setError(e)) }).catch(e => this.setError(e))
} }
@@ -211,7 +211,7 @@ export class AppShowPage {
spinner: 'lines', spinner: 'lines',
cssClass: 'loader', cssClass: 'loader',
}).displayDuringP( }).displayDuringP(
this.apiService.startPackage({ id: this.pkgId }), this.embassyApi.startPackage({ id: this.pkgId }),
).catch(e => this.setError(e)) ).catch(e => this.setError(e))
} }
@@ -235,7 +235,8 @@ export class AppShowPage {
title: 'Monitor', title: 'Monitor',
icon: 'medkit-outline', icon: 'medkit-outline',
color: 'danger', color: 'danger',
disabled: [], // @TODO make the disabled check better. Don't want to list every status here. Monitor should be disabled except is pkg is running.
disabled: [FEStatus.Installing, FEStatus.Updating, FEStatus.Removing, FEStatus.BackingUp, FEStatus.Restoring],
}, },
{ {
action: () => this.navCtrl.navigateForward(['config'], { relativeTo: this.route }), action: () => this.navCtrl.navigateForward(['config'], { relativeTo: this.route }),

View File

@@ -5,6 +5,7 @@ import { IonicModule } from '@ionic/angular'
import { AppReleaseNotes } from './app-release-notes.page' import { AppReleaseNotes } from './app-release-notes.page'
import { PwaBackComponentModule } from 'src/app/components/pwa-back-button/pwa-back.component.module' import { PwaBackComponentModule } from 'src/app/components/pwa-back-button/pwa-back.component.module'
import { SharingModule } from 'src/app/modules/sharing.module' import { SharingModule } from 'src/app/modules/sharing.module'
import { TextSpinnerComponentModule } from 'src/app/components/text-spinner/text-spinner.component.module'
const routes: Routes = [ const routes: Routes = [
{ {
@@ -20,6 +21,7 @@ const routes: Routes = [
RouterModule.forChild(routes), RouterModule.forChild(routes),
PwaBackComponentModule, PwaBackComponentModule,
SharingModule, SharingModule,
TextSpinnerComponentModule,
], ],
declarations: [AppReleaseNotes], declarations: [AppReleaseNotes],
}) })

View File

@@ -8,7 +8,7 @@
</ion-header> </ion-header>
<ion-content> <ion-content>
<ion-spinner *ngIf="!marketplaceService.releaseNotes[pkgId]; else loaded" class="center" name="lines" color="warning"></ion-spinner> <text-spinner *ngIf="!marketplaceService.releaseNotes[pkgId]; else loaded" text="Loading Release Notes"></text-spinner>
<ng-template #loaded> <ng-template #loaded>
<div *ngFor="let note of marketplaceService.releaseNotes[pkgId] | keyvalue : asIsOrder"> <div *ngFor="let note of marketplaceService.releaseNotes[pkgId] | keyvalue : asIsOrder">

View File

@@ -53,7 +53,7 @@
<ion-label> <ion-label>
<h2 style="font-family: 'Montserrat';">{{ pkg.manifest.title }}</h2> <h2 style="font-family: 'Montserrat';">{{ pkg.manifest.title }}</h2>
<p>{{ pkg.manifest.description.short }}</p> <p>{{ pkg.manifest.description.short }}</p>
<ng-container *ngIf="patch.data['package-data'][pkg.id] as localPkg"> <ng-container *ngIf="localPkgs[pkg.id] as localPkg">
<p *ngIf="localPkg.state === PackageState.Installed"> <p *ngIf="localPkg.state === PackageState.Installed">
<ion-text *ngIf="(pkg.manifest.version | compareEmver : localPkg.manifest.version) === 0" color="success">Installed</ion-text> <ion-text *ngIf="(pkg.manifest.version | compareEmver : localPkg.manifest.version) === 0" color="success">Installed</ion-text>
<ion-text *ngIf="(pkg.manifest.version | compareEmver : localPkg.manifest.version) === 1" color="warning">Update Available</ion-text> <ion-text *ngIf="(pkg.manifest.version | compareEmver : localPkg.manifest.version) === 1" color="warning">Update Available</ion-text>

View File

@@ -3,12 +3,12 @@ import { MarketplaceData, MarketplaceEOS, MarketplacePkg } from 'src/app/service
import { wizardModal } from 'src/app/components/install-wizard/install-wizard.component' import { wizardModal } from 'src/app/components/install-wizard/install-wizard.component'
import { IonContent, ModalController } from '@ionic/angular' import { IonContent, ModalController } from '@ionic/angular'
import { WizardBaker } from 'src/app/components/install-wizard/prebaked-wizards' import { WizardBaker } from 'src/app/components/install-wizard/prebaked-wizards'
import { PatchDbService } from 'src/app/services/patch-db/patch-db.service' import { PackageDataEntry, PackageState } from 'src/app/services/patch-db/data-model'
import { PackageState } from 'src/app/services/patch-db/data-model'
import { Subscription } from 'rxjs' import { Subscription } from 'rxjs'
import { ErrorToastService } from 'src/app/services/error-toast.service' import { ErrorToastService } from 'src/app/services/error-toast.service'
import { MarketplaceService } from '../marketplace.service' import { MarketplaceService } from '../marketplace.service'
import { MarketplaceApiService } from 'src/app/services/api/marketplace/marketplace-api.service' import { MarketplaceApiService } from 'src/app/services/api/marketplace/marketplace-api.service'
import { PatchDbService } from 'src/app/services/patch-db/patch-db.service'
@Component({ @Component({
selector: 'marketplace-list', selector: 'marketplace-list',
@@ -17,6 +17,8 @@ import { MarketplaceApiService } from 'src/app/services/api/marketplace/marketpl
}) })
export class MarketplaceListPage { export class MarketplaceListPage {
@ViewChild(IonContent) content: IonContent @ViewChild(IonContent) content: IonContent
localPkgs: { [id: string]: PackageDataEntry }
pageLoading = true pageLoading = true
pkgsLoading = true pkgsLoading = true
@@ -37,7 +39,7 @@ export class MarketplaceListPage {
constructor ( constructor (
private readonly marketplaceService: MarketplaceService, private readonly marketplaceService: MarketplaceService,
private readonly marketplaceApiService: MarketplaceApiService, private readonly marketplaceApi: MarketplaceApiService,
private readonly modalCtrl: ModalController, private readonly modalCtrl: ModalController,
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly wizardBaker: WizardBaker, private readonly wizardBaker: WizardBaker,
@@ -45,11 +47,16 @@ export class MarketplaceListPage {
) { } ) { }
async ngOnInit () { async ngOnInit () {
this.subs = [
this.patch.watch$('package-data').subscribe(pkgs => {
this.localPkgs = pkgs
}),
]
try { try {
const [data, eos] = await Promise.all([ const [data, eos] = await Promise.all([
this.marketplaceApiService.getMarketplaceData({ }), this.marketplaceApi.getMarketplaceData({ }),
this.marketplaceApiService.getEos({ }), this.marketplaceApi.getEos({ }),
this.getPkgs(), this.getPkgs(),
]) ])
this.eos = eos this.eos = eos
@@ -107,7 +114,7 @@ export class MarketplaceListPage {
if (this.pkgs.length) { if (this.pkgs.length) {
this.pkgsLoading = false this.pkgsLoading = false
} }
await this.marketplaceService.getUpdates(this.patch.data['package-data']) await this.marketplaceService.getUpdates(this.localPkgs)
this.pkgs = this.marketplaceService.updates this.pkgs = this.marketplaceService.updates
} else { } else {
const pkgs = await this.marketplaceService.getPkgs( const pkgs = await this.marketplaceService.getPkgs(

View File

@@ -12,32 +12,30 @@ export class MarketplaceService {
updates: MarketplacePkg[] = null updates: MarketplacePkg[] = null
releaseNotes: { [id: string]: { releaseNotes: { [id: string]: {
[version: string]: string [version: string]: string
} } } } = { }
constructor ( constructor (
private readonly marketplaceApiService: MarketplaceApiService, private readonly marketplaceApi: MarketplaceApiService,
private readonly emver: Emver, private readonly emver: Emver,
) { } ) { }
async getUpdates (pkgData: { [id: string]: PackageDataEntry}) : Promise<MarketplacePkg[]> { async getUpdates (localPkgs: { [id: string]: PackageDataEntry }) : Promise<void> {
const idAndCurrentVersions = Object.keys(pkgData).map(key => ({ id: key, version: pkgData[key].manifest.version })) const idAndCurrentVersions = Object.keys(localPkgs).map(key => ({ id: key, version: localPkgs[key].manifest.version }))
console.log(JSON.stringify(idAndCurrentVersions)) const latestPkgs = (await this.marketplaceApi.getMarketplacePkgs({
const latestPkgs = (await this.marketplaceApiService.getMarketplacePkgs({
ids: idAndCurrentVersions, ids: idAndCurrentVersions,
})) }))
const updates = latestPkgs.filter(latestPkg => { const updates = latestPkgs.filter(latestPkg => {
const latestVersion = latestPkg.manifest.version const latestVersion = latestPkg.manifest.version
const curVersion = pkgData[latestPkg.manifest.id]?.manifest.version const curVersion = localPkgs[latestPkg.manifest.id]?.manifest.version
return !!curVersion && this.emver.compare(latestVersion, curVersion) === 1 return !!curVersion && this.emver.compare(latestVersion, curVersion) === 1
}) })
this.updates = updates this.updates = updates
return updates
} }
async getPkgs (category: string, query: string, page: number, perPage: number) : Promise<MarketplacePkg[]> { async getPkgs (category: string, query: string, page: number, perPage: number) : Promise<MarketplacePkg[]> {
const pkgs = await this.marketplaceApiService.getMarketplacePkgs({ const pkgs = await this.marketplaceApi.getMarketplacePkgs({
category: category !== 'all' ? category : undefined, category: category !== 'all' ? category : undefined,
query, query,
page: String(page), page: String(page),
@@ -51,7 +49,10 @@ export class MarketplaceService {
} }
async getPkg (id: string, version?: string): Promise<void> { async getPkg (id: string, version?: string): Promise<void> {
const pkg = (await this.marketplaceApiService.getMarketplacePkgs({ ids: [{ id, version }]}))[0] const pkgs = await this.marketplaceApi.getMarketplacePkgs({
ids: [{ id, version: version || '*' }],
})
const pkg = pkgs[0]
if (pkg) { if (pkg) {
this.pkgs[id] = pkg this.pkgs[id] = pkg
} else { } else {
@@ -60,7 +61,7 @@ export class MarketplaceService {
} }
async getReleaseNotes (id: string): Promise<void> { async getReleaseNotes (id: string): Promise<void> {
this.releaseNotes[id] = await this.marketplaceApiService.getReleaseNotes({ id }) this.releaseNotes[id] = await this.marketplaceApi.getReleaseNotes({ id })
} }
} }

View File

@@ -20,7 +20,7 @@ export class NotificationsPage {
readonly perPage = 20 readonly perPage = 20
constructor ( constructor (
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly loader: LoaderService, private readonly loader: LoaderService,
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly alertCtrl: AlertController, private readonly alertCtrl: AlertController,
@@ -48,7 +48,7 @@ export class NotificationsPage {
async getNotifications (): Promise<ServerNotifications> { async getNotifications (): Promise<ServerNotifications> {
let notifications: ServerNotifications = [] let notifications: ServerNotifications = []
try { try {
notifications = await this.apiService.getNotifications({ page: this.page, 'per-page': this.perPage }) notifications = await this.embassyApi.getNotifications({ page: this.page, 'per-page': this.perPage })
this.needInfinite = notifications.length >= this.perPage this.needInfinite = notifications.length >= this.perPage
this.page++ this.page++
} catch (e) { } catch (e) {
@@ -65,7 +65,7 @@ export class NotificationsPage {
spinner: 'lines', spinner: 'lines',
cssClass: 'loader', cssClass: 'loader',
}).displayDuringP( }).displayDuringP(
this.apiService.deleteNotification({ id }).then(() => { this.embassyApi.deleteNotification({ id }).then(() => {
this.notifications.splice(index, 1) this.notifications.splice(index, 1)
}), }),
).catch(e => { ).catch(e => {

View File

@@ -7,7 +7,7 @@
</ion-toolbar> </ion-toolbar>
</ion-header> </ion-header>
<ion-content class="ion-padding-top" *ngIf="patch.data['server-info] as server"> <ion-content class="ion-padding-top" *ngIf="patch.data['server-info'] as server">
<ion-item-group> <ion-item-group>
<ion-item detail="true" button [routerLink]="['ssh-keys']"> <ion-item detail="true" button [routerLink]="['ssh-keys']">

View File

@@ -10,7 +10,7 @@ export class SSHService {
private readonly keys$ = new BehaviorSubject<SSHKeys>({ }) private readonly keys$ = new BehaviorSubject<SSHKeys>({ })
constructor ( constructor (
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
) { } ) { }
watch$ () { watch$ () {
@@ -18,18 +18,18 @@ export class SSHService {
} }
async getKeys (): Promise<void> { async getKeys (): Promise<void> {
const keys = await this.apiService.getSshKeys({ }) const keys = await this.embassyApi.getSshKeys({ })
this.keys$.next(keys) this.keys$.next(keys)
} }
async add (pubkey: string): Promise<void> { async add (pubkey: string): Promise<void> {
const key = await this.apiService.addSshKey({ pubkey }) const key = await this.embassyApi.addSshKey({ pubkey })
const keys = this.keys$.getValue() const keys = this.keys$.getValue()
this.keys$.next({ ...keys, ...key }) this.keys$.next({ ...keys, ...key })
} }
async delete (hash: string): Promise<void> { async delete (hash: string): Promise<void> {
await this.apiService.deleteSshKey({ hash }) await this.embassyApi.deleteSshKey({ hash })
const keys = this.keys$.getValue() const keys = this.keys$.getValue()
const filtered = Object.keys(keys) const filtered = Object.keys(keys)

View File

@@ -26,7 +26,7 @@ export class LANPage {
private readonly toastCtrl: ToastController, private readonly toastCtrl: ToastController,
private readonly config: ConfigService, private readonly config: ConfigService,
private readonly loader: LoaderService, private readonly loader: LoaderService,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly patch: PatchDbService, private readonly patch: PatchDbService,
) { } ) { }
@@ -54,7 +54,7 @@ export class LANPage {
spinner: 'lines', spinner: 'lines',
cssClass: 'loader', cssClass: 'loader',
}).displayDuringAsync( async () => { }).displayDuringAsync( async () => {
await this.apiService.refreshLan({ }) await this.embassyApi.refreshLan({ })
}).catch(e => { }).catch(e => {
console.error(e) console.error(e)
}) })

View File

@@ -17,7 +17,7 @@ export class ServerBackupPage {
constructor ( constructor (
private readonly modalCtrl: ModalController, private readonly modalCtrl: ModalController,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly loadingCtrl: LoadingController, private readonly loadingCtrl: LoadingController,
) { } ) { }
@@ -32,7 +32,7 @@ export class ServerBackupPage {
async getExternalDisks (): Promise<void> { async getExternalDisks (): Promise<void> {
try { try {
this.disks = await this.apiService.getDisks({ }) this.disks = await this.embassyApi.getDisks({ })
this.allPartitionsMounted = Object.values(this.disks).every(d => Object.values(d.partitions).every(p => p['is-mounted'])) this.allPartitionsMounted = Object.values(this.disks).every(d => Object.values(d.partitions).every(p => p['is-mounted']))
} catch (e) { } catch (e) {
console.error(e) console.error(e)
@@ -70,7 +70,7 @@ export class ServerBackupPage {
await loader.present() await loader.present()
try { try {
await this.apiService.createBackup({ logicalname, password }) await this.embassyApi.createBackup({ logicalname, password })
} catch (e) { } catch (e) {
console.error(e) console.error(e)
this.error = e.message this.error = e.message

View File

@@ -15,7 +15,7 @@ export class ServerLogsPage {
constructor ( constructor (
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
) { } ) { }
ngOnInit () { ngOnInit () {
@@ -26,7 +26,7 @@ export class ServerLogsPage {
this.logs = '' this.logs = ''
this.loading = true this.loading = true
try { try {
const logs = await this.apiService.getServerLogs({ }) const logs = await this.embassyApi.getServerLogs({ })
this.logs = logs.map(l => `${l.timestamp} ${l.log}`).join('\n\n') this.logs = logs.map(l => `${l.timestamp} ${l.log}`).join('\n\n')
setTimeout(async () => await this.content.scrollToBottom(100), 200) setTimeout(async () => await this.content.scrollToBottom(100), 200)
} catch (e) { } catch (e) {

View File

@@ -16,7 +16,7 @@ export class ServerMetricsPage {
constructor ( constructor (
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
) { } ) { }
ngOnInit () { ngOnInit () {
@@ -41,7 +41,7 @@ export class ServerMetricsPage {
async getMetrics (): Promise<void> { async getMetrics (): Promise<void> {
try { try {
this.metrics = await this.apiService.getServerMetrics({ }) this.metrics = await this.embassyApi.getServerMetrics({ })
} catch (e) { } catch (e) {
console.error(e) console.error(e)
this.errToast.present(e.message) this.errToast.present(e.message)

View File

@@ -16,7 +16,7 @@ export class ServerShowPage {
constructor ( constructor (
private readonly alertCtrl: AlertController, private readonly alertCtrl: AlertController,
private readonly loader: LoaderService, private readonly loader: LoaderService,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly navCtrl: NavController, private readonly navCtrl: NavController,
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
) { } ) { }
@@ -73,7 +73,7 @@ export class ServerShowPage {
this.loader this.loader
.of(LoadingSpinner(`Restarting...`)) .of(LoadingSpinner(`Restarting...`))
.displayDuringAsync( async () => { .displayDuringAsync( async () => {
await this.apiService.restartServer({ }) await this.embassyApi.restartServer({ })
}) })
.catch(console.error) .catch(console.error)
} }
@@ -82,7 +82,7 @@ export class ServerShowPage {
this.loader this.loader
.of(LoadingSpinner(`Shutting down...`)) .of(LoadingSpinner(`Shutting down...`))
.displayDuringAsync( async () => { .displayDuringAsync( async () => {
await this.apiService.shutdownServer({ }) await this.embassyApi.shutdownServer({ })
}) })
.catch(console.error) .catch(console.error)
} }
@@ -91,9 +91,9 @@ export class ServerShowPage {
this.settings = { this.settings = {
'Settings': [ 'Settings': [
{ {
title: 'Preferences', title: 'Privacy and Security',
icon: 'cog-outline', icon: 'shield-checkmark-outline',
action: () => this.navCtrl.navigateForward(['preferences'], { relativeTo: this.route }), action: () => this.navCtrl.navigateForward(['privacy'], { relativeTo: this.route }),
}, },
{ {
title: 'LAN', title: 'LAN',

View File

@@ -19,7 +19,7 @@ export class WifiAddPage {
constructor ( constructor (
private readonly navCtrl: NavController, private readonly navCtrl: NavController,
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly loader: LoaderService, private readonly loader: LoaderService,
private readonly wifiService: WifiService, private readonly wifiService: WifiService,
) { } ) { }
@@ -30,7 +30,7 @@ export class WifiAddPage {
spinner: 'lines', spinner: 'lines',
cssClass: 'loader', cssClass: 'loader',
}).displayDuringAsync(async () => { }).displayDuringAsync(async () => {
await this.apiService.addWifi({ await this.embassyApi.addWifi({
ssid: this.ssid, ssid: this.ssid,
password: this.password, password: this.password,
country: this.countryCode, country: this.countryCode,
@@ -50,7 +50,7 @@ export class WifiAddPage {
spinner: 'lines', spinner: 'lines',
cssClass: 'loader', cssClass: 'loader',
}).displayDuringAsync(async () => { }).displayDuringAsync(async () => {
await this.apiService.addWifi({ await this.embassyApi.addWifi({
ssid: this.ssid, ssid: this.ssid,
password: this.password, password: this.password,
country: this.countryCode, country: this.countryCode,

View File

@@ -18,7 +18,7 @@ export class WifiListPage {
subs: Subscription[] = [] subs: Subscription[] = []
constructor ( constructor (
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly loader: LoaderService, private readonly loader: LoaderService,
private readonly errToast: ErrorToastService, private readonly errToast: ErrorToastService,
private readonly actionCtrl: ActionSheetController, private readonly actionCtrl: ActionSheetController,
@@ -62,7 +62,7 @@ export class WifiListPage {
spinner: 'lines', spinner: 'lines',
cssClass: 'loader', cssClass: 'loader',
}).displayDuringAsync(async () => { }).displayDuringAsync(async () => {
await this.apiService.connectWifi({ ssid }) await this.embassyApi.connectWifi({ ssid })
this.wifiService.confirmWifi(ssid) this.wifiService.confirmWifi(ssid)
}).catch(e => { }).catch(e => {
console.error(e) console.error(e)
@@ -76,7 +76,7 @@ export class WifiListPage {
spinner: 'lines', spinner: 'lines',
cssClass: 'loader', cssClass: 'loader',
}).displayDuringAsync(async () => { }).displayDuringAsync(async () => {
await this.apiService.deleteWifi({ ssid }) await this.embassyApi.deleteWifi({ ssid })
}).catch(e => { }).catch(e => {
console.error(e) console.error(e)
this.errToast.present(e.message) this.errToast.present(e.message)

View File

@@ -1,27 +0,0 @@
import { Pipe, PipeTransform } from '@angular/core'
import { combineLatest, Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { PatchDbService } from '../services/patch-db/patch-db.service'
import { FEStatus, renderPkgStatus } from '../services/pkg-status-rendering.service'
@Pipe({
name: 'status',
})
export class StatusPipe implements PipeTransform {
constructor (
private readonly patch: PatchDbService,
) { }
transform (pkgId: string): Observable<FEStatus> {
return combineLatest([
this.patch.watch$('package-data', pkgId, 'state'),
this.patch.watch$('package-data', pkgId, 'installed', 'status'),
])
.pipe(
map(([state, status]) => {
return renderPkgStatus(state, status).feStatus
}),
)
}
}

View File

@@ -1,6 +1,6 @@
import { Pipe, PipeTransform } from '@angular/core' import { Pipe, PipeTransform } from '@angular/core'
import { PackageDataEntry, Manifest } from '../services/patch-db/data-model' import { PackageDataEntry } from '../services/patch-db/data-model'
import { ConfigService, getManifest, hasUi } from '../services/config.service' import { ConfigService, hasUi } from '../services/config.service'
@Pipe({ @Pipe({
name: 'hasUi', name: 'hasUi',
@@ -8,7 +8,7 @@ import { ConfigService, getManifest, hasUi } from '../services/config.service'
export class HasUiPipe implements PipeTransform { export class HasUiPipe implements PipeTransform {
transform (pkg: PackageDataEntry): boolean { transform (pkg: PackageDataEntry): boolean {
const interfaces = getManifest(pkg).interfaces const interfaces = pkg.manifest.interfaces
return hasUi(interfaces) return hasUi(interfaces)
} }
} }

View File

@@ -1,4 +1,4 @@
import { DockerIoFormat, Manifest, PackageDataEntry, PackageMainStatus, PackageState } from 'src/app/services/patch-db/data-model' import { DependencyErrorType, DockerIoFormat, Manifest, PackageDataEntry, PackageMainStatus, PackageState } from 'src/app/services/patch-db/data-model'
import { MarketplacePkg, Metric, NotificationLevel, RR, ServerNotifications } from './api.types' import { MarketplacePkg, Metric, NotificationLevel, RR, ServerNotifications } from './api.types'
export module Mock { export module Mock {
@@ -1347,56 +1347,56 @@ export module Mock {
// 'install-progress': undefined, // 'install-progress': undefined,
// } // }
// export const lnd: PackageDataEntry = { export const lnd: PackageDataEntry = {
// state: PackageState.Installed, state: PackageState.Installed,
// 'static-files': { 'static-files': {
// license: 'licenseUrl', // /public/package-data/lnd/0.21.1/LICENSE.md, license: 'licenseUrl', // /public/package-data/lnd/0.21.1/LICENSE.md,
// icon: 'assets/img/service-icons/lnd.png', icon: 'assets/img/service-icons/lnd.png',
// instructions: 'instructionsUrl', // /public/package-data/lnd/0.21.1/INSTRUCTIONS.md instructions: 'instructionsUrl', // /public/package-data/lnd/0.21.1/INSTRUCTIONS.md
// }, },
// manifest: MockManifestLnd, manifest: MockManifestLnd,
// installed: { installed: {
// status: { status: {
// configured: true, configured: true,
// main: { main: {
// status: PackageMainStatus.Stopped, status: PackageMainStatus.Stopped,
// }, },
// 'dependency-errors': { 'dependency-errors': {
// 'bitcoin-proxy': { 'bitcoin-proxy': {
// type: DependencyErrorType.NotInstalled, type: DependencyErrorType.NotInstalled,
// title: Mock.MockManifestBitcoinProxy.title, title: Mock.MockManifestBitcoinProxy.title,
// icon: 'assets/img/service-icons/bitcoin-proxy.png', icon: 'assets/img/service-icons/bitcoin-proxy.png',
// }, },
// }, },
// }, },
// 'interface-info': { 'interface-info': {
// ip: '10.0.0.1', ip: '10.0.0.1',
// addresses: { addresses: {
// rpc: { rpc: {
// 'tor-address': 'lnd-rpc-address.onion', 'tor-address': 'lnd-rpc-address.onion',
// 'lan-address': 'lnd-rpc-address.local', 'lan-address': 'lnd-rpc-address.local',
// }, },
// grpc: { grpc: {
// 'tor-address': 'lnd-grpc-address.onion', 'tor-address': 'lnd-grpc-address.onion',
// 'lan-address': 'lnd-grpc-address.local', 'lan-address': 'lnd-grpc-address.local',
// }, },
// }, },
// }, },
// 'system-pointers': [], 'system-pointers': [],
// 'current-dependents': { }, 'current-dependents': { },
// 'current-dependencies': { 'current-dependencies': {
// 'bitcoind': { 'bitcoind': {
// pointers: [], pointers: [],
// 'health-checks': [], 'health-checks': [],
// }, },
// 'bitcoin-proxy': { 'bitcoin-proxy': {
// pointers: [], pointers: [],
// 'health-checks': [], 'health-checks': [],
// }, },
// }, },
// }, },
// 'install-progress': undefined, 'install-progress': undefined,
// } }
// export const DbDump: RR.GetDumpRes = { // export const DbDump: RR.GetDumpRes = {
// id: 1, // id: 1,

View File

@@ -2,7 +2,7 @@ import { Injectable } from '@angular/core'
import { pauseFor } from '../../../util/misc.util' import { pauseFor } from '../../../util/misc.util'
import { ApiService } from './embassy-api.service' import { ApiService } from './embassy-api.service'
import { Operation, PatchOp } from 'patch-db-client' import { Operation, PatchOp } from 'patch-db-client'
import { PackageDataEntry, PackageMainStatus, PackageState, ServerStatus } from 'src/app/services/patch-db/data-model' import { DataModel, InstallProgress, PackageDataEntry, PackageMainStatus, PackageState, ServerStatus } from 'src/app/services/patch-db/data-model'
import { RR, WithRevision } from '../api.types' import { RR, WithRevision } from '../api.types'
import { parsePropertiesPermissive } from 'src/app/util/properties.util' import { parsePropertiesPermissive } from 'src/app/util/properties.util'
import { Mock } from '../api.fixures' import { Mock } from '../api.fixures'
@@ -325,18 +325,19 @@ export class MockApiService extends ApiService {
async installPackageRaw (params: RR.InstallPackageReq): Promise<RR.InstallPackageRes> { async installPackageRaw (params: RR.InstallPackageReq): Promise<RR.InstallPackageRes> {
await pauseFor(2000) await pauseFor(2000)
const initialProgress: InstallProgress = {
size: 120,
downloaded: 0,
'download-complete': false,
validated: 0,
'validation-complete': false,
unpacked: 0,
'unpack-complete': false,
}
const pkg: PackageDataEntry = { const pkg: PackageDataEntry = {
...Mock.bitcoinproxy, ...Mock[params.id],
state: PackageState.Installing, state: PackageState.Installing,
'install-progress': { 'install-progress': initialProgress,
size: 100,
downloaded: 10,
'download-complete': false,
validated: 1,
'validation-complete': true,
read: 50,
'read-complete': false,
},
} }
const patch = [ const patch = [
{ {
@@ -345,7 +346,11 @@ export class MockApiService extends ApiService {
value: pkg, value: pkg,
}, },
] ]
return this.http.rpcRequest<WithRevision<null>>({ method: 'db.patch', params: { patch } }) const res = await this.http.rpcRequest<WithRevision<null>>({ method: 'db.patch', params: { patch } })
setTimeout(async () => {
this.updateProgress(params.id, initialProgress)
}, 1000)
return res
} }
async dryUpdatePackage (params: RR.DryUpdatePackageReq): Promise<RR.DryUpdatePackageRes> { async dryUpdatePackage (params: RR.DryUpdatePackageReq): Promise<RR.DryUpdatePackageRes> {
@@ -483,4 +488,45 @@ export class MockApiService extends ApiService {
await pauseFor(2000) await pauseFor(2000)
return { } return { }
} }
private async updateProgress (id: string, initialProgress: InstallProgress) {
const phases = [
{ progress: 'downloaded', completion: 'download-complete'},
{ progress: 'validated', completion: 'validation-complete'},
{ progress: 'unpacked', completion: 'unpack-complete'},
]
for (let phase of phases) {
let i = initialProgress[phase.progress]
console.log('PHASE', phase)
console.log('Initial i', i)
while (i < initialProgress.size) {
console.log(i)
await pauseFor(1000)
i = Math.min(i + 40, initialProgress.size)
initialProgress[phase.progress] = i
if (i === initialProgress.size) {
initialProgress[phase.completion] = true
}
const patch = [
{
op: PatchOp.REPLACE,
path: `/package-data/${id}/install-progress`,
value: initialProgress,
},
]
await this.http.rpcRequest<WithRevision<null>>({ method: 'db.patch', params: { patch } })
}
}
setTimeout(() => {
const patch = [
{
op: PatchOp.REPLACE,
path: `/package-data/${id}/state`,
value: PackageState.Installed,
},
]
this.http.rpcRequest<WithRevision<null>>({ method: 'db.patch', params: { patch } })
}, 1000)
}
} }

View File

@@ -1,14 +1,28 @@
import { RR } from '../api.types' import { RR } from '../api.types'
import { ConfigService } from '../../config.service' import { ConfigService } from '../../config.service'
import { PatchDbService } from '../../patch-db/patch-db.service' import { PatchDbService } from '../../patch-db/patch-db.service'
import { ServerInfo } from '../../patch-db/data-model'
import { AuthState } from '../../auth.service'
import { takeWhile } from 'rxjs/operators'
export abstract class MarketplaceApiService { export abstract class MarketplaceApiService {
private server: ServerInfo
constructor ( constructor (
readonly config: ConfigService, readonly config: ConfigService,
readonly patch: PatchDbService, readonly patch: PatchDbService,
) { } ) { }
init (auth: AuthState) {
this.patch.watch$('server-info')
.pipe(
takeWhile(() => auth === AuthState.VERIFIED),
)
.subscribe(server => {
this.server = server
})
}
abstract getEos (params: RR.GetMarketplaceEOSReq): Promise<RR.GetMarketplaceEOSRes> abstract getEos (params: RR.GetMarketplaceEOSReq): Promise<RR.GetMarketplaceEOSRes>
abstract getMarketplaceData (params: RR.GetMarketplaceDataReq): Promise<RR.GetMarketplaceDataRes> abstract getMarketplaceData (params: RR.GetMarketplaceDataReq): Promise<RR.GetMarketplaceDataRes>
@@ -20,11 +34,11 @@ export abstract class MarketplaceApiService {
abstract getLatestVersion (params: RR.GetLatestVersionReq): Promise<RR.GetLatestVersionRes> abstract getLatestVersion (params: RR.GetLatestVersionReq): Promise<RR.GetLatestVersionRes>
getMarketplaceURL (type: 'eos' | 'package', defaultToTor = false): string { getMarketplaceURL (type: 'eos' | 'package', defaultToTor = false): string {
const packageMarketplace = this.patch.data['server-info']['package-marketplace'] const packageMarketplace = this.server['package-marketplace']
if (defaultToTor && !packageMarketplace) { if (defaultToTor && !packageMarketplace) {
return this.config.start9Marketplace.tor return this.config.start9Marketplace.tor
} }
const eosMarketplace = this.patch.data['server-info']['eos-marketplace'] || this.config.start9Marketplace.clearnet const eosMarketplace = this.server['eos-marketplace'] || this.config.start9Marketplace.clearnet
if (type === 'eos') { if (type === 'eos') {
return eosMarketplace return eosMarketplace
} else { } else {

View File

@@ -17,7 +17,7 @@ export class AuthService {
private readonly authState$: BehaviorSubject<AuthState> = new BehaviorSubject(AuthState.INITIALIZING) private readonly authState$: BehaviorSubject<AuthState> = new BehaviorSubject(AuthState.INITIALIZING)
constructor ( constructor (
private readonly api: ApiService, private readonly embassyApi: ApiService,
private readonly storage: Storage, private readonly storage: Storage,
) { } ) { }
@@ -31,7 +31,7 @@ export class AuthService {
} }
async login (password: string): Promise<void> { async login (password: string): Promise<void> {
await this.api.login({ password }) await this.embassyApi.login({ password })
await this.storage.set(this.LOGGED_IN_KEY, true) await this.storage.set(this.LOGGED_IN_KEY, true)
this.authState$.next(AuthState.VERIFIED) this.authState$.next(AuthState.VERIFIED)
} }

View File

@@ -101,13 +101,6 @@ export function hasUi (interfaces: { [id: string]: InterfaceDef }): boolean {
return hasTorUi(interfaces) || hasLanUi(interfaces) return hasTorUi(interfaces) || hasLanUi(interfaces)
} }
export function getManifest (pkg: PackageDataEntry): Manifest {
if (pkg.state === PackageState.Installed) {
return pkg.manifest
}
return pkg['temp-manifest']
}
function removeProtocol (str: string): string { function removeProtocol (str: string): string {
if (str.startsWith('http://')) return str.slice(7) if (str.startsWith('http://')) return str.slice(7)
if (str.startsWith('https://')) return str.slice(8) if (str.startsWith('https://')) return str.slice(8)

View File

@@ -2,8 +2,9 @@ import { Injectable } from '@angular/core'
import { BehaviorSubject, combineLatest, fromEvent, merge, Subscription } from 'rxjs' import { BehaviorSubject, combineLatest, fromEvent, merge, Subscription } from 'rxjs'
import { ConnectionStatus, PatchDbService } from './patch-db/patch-db.service' import { ConnectionStatus, PatchDbService } from './patch-db/patch-db.service'
import { HttpService, Method } from './http.service' import { HttpService, Method } from './http.service'
import { distinctUntilChanged } from 'rxjs/operators' import { distinctUntilChanged, takeWhile } from 'rxjs/operators'
import { ConfigService } from './config.service' import { ConfigService } from './config.service'
import { AuthState } from './auth.service'
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@@ -23,16 +24,35 @@ export class ConnectionService {
return this.connectionFailure$.asObservable() return this.connectionFailure$.asObservable()
} }
start () { start (auth: AuthState) {
this.subs = [ this.subs = [
merge(fromEvent(window, 'online'), fromEvent(window, 'offline')) merge(fromEvent(window, 'online'), fromEvent(window, 'offline'))
.pipe(
takeWhile(() => auth === AuthState.VERIFIED),
)
.subscribe(event => { .subscribe(event => {
this.networkState$.next(event.type === 'online') this.networkState$.next(event.type === 'online')
}), }),
combineLatest([this.networkState$.pipe(distinctUntilChanged()), this.patch.watchConnection$().pipe(distinctUntilChanged())]) combineLatest([
.subscribe(async ([network, connectionStatus]) => { // 1
const addrs = this.patch.data['server-info']['connection-addresses'] this.networkState$
.pipe(
distinctUntilChanged(),
),
// 2
this.patch.watchConnection$()
.pipe(
distinctUntilChanged(),
),
// 3
this.patch.watch$('server-info', 'connection-addresses')
.pipe(
takeWhile(() => auth === AuthState.VERIFIED),
distinctUntilChanged(),
),
])
.subscribe(async ([network, connectionStatus, addrs]) => {
if (connectionStatus !== ConnectionStatus.Disconnected) { if (connectionStatus !== ConnectionStatus.Disconnected) {
this.connectionFailure$.next(ConnectionFailure.None) this.connectionFailure$.next(ConnectionFailure.None)
} else if (!network) { } else if (!network) {
@@ -61,13 +81,6 @@ export class ConnectionService {
] ]
} }
stop () {
this.subs.forEach(sub => {
sub.unsubscribe()
})
this.subs = []
}
private async testAddrs (addrs: string[]): Promise<boolean> { private async testAddrs (addrs: string[]): Promise<boolean> {
if (!addrs.length) return true if (!addrs.length) return true

View File

@@ -70,6 +70,12 @@ export class HttpService {
this.fullUrl + httpOpts.url : this.fullUrl + httpOpts.url :
httpOpts.url httpOpts.url
Object.keys(httpOpts.params).forEach(key => {
if (httpOpts.params[key] === undefined) {
delete httpOpts.params[key]
}
})
return { return {
observe: 'events', observe: 'events',
responseType: 'json', responseType: 'json',

View File

@@ -62,8 +62,8 @@ export interface InstallProgress {
'download-complete': boolean 'download-complete': boolean
validated: number validated: number
'validation-complete': boolean 'validation-complete': boolean
read: number unpacked: number
'read-complete': boolean 'unpack-complete': boolean
} }
export interface InstalledPackageDataEntry { export interface InstalledPackageDataEntry {

View File

@@ -8,7 +8,7 @@ import { ApiService } from 'src/app/services/api/embassy/embassy-api.service'
export function PatchDbServiceFactory ( export function PatchDbServiceFactory (
config: ConfigService, config: ConfigService,
bootstrapper: LocalStorageBootstrap, bootstrapper: LocalStorageBootstrap,
apiService: ApiService, embassyApi: ApiService,
): PatchDbService { ): PatchDbService {
const { mocks, patchDb: { poll }, isConsulate } = config const { mocks, patchDb: { poll }, isConsulate } = config
@@ -17,13 +17,13 @@ export function PatchDbServiceFactory (
if (mocks.enabled) { if (mocks.enabled) {
if (mocks.connection === 'poll') { if (mocks.connection === 'poll') {
source = new PollSource({ ...poll }, apiService) source = new PollSource({ ...poll }, embassyApi)
} else { } else {
source = new WebsocketSource(`ws://localhost:${config.mocks.wsPort}/db`) source = new WebsocketSource(`ws://localhost:${config.mocks.wsPort}/db`)
} }
} else { } else {
if (isConsulate) { if (isConsulate) {
source = new PollSource({ ...poll }, apiService) source = new PollSource({ ...poll }, embassyApi)
} else { } else {
const protocol = window.location.protocol === 'http:' ? 'ws' : 'wss' const protocol = window.location.protocol === 'http:' ? 'ws' : 'wss'
const host = window.location.host const host = window.location.host
@@ -31,5 +31,5 @@ export function PatchDbServiceFactory (
} }
} }
return new PatchDbService(source, apiService, bootstrapper) return new PatchDbService(source, embassyApi, bootstrapper)
} }

View File

@@ -20,10 +20,11 @@ export enum ConnectionStatus {
}) })
export class PatchDbService { export class PatchDbService {
connectionStatus$ = new BehaviorSubject(ConnectionStatus.Initializing) connectionStatus$ = new BehaviorSubject(ConnectionStatus.Initializing)
data: DataModel
private patchDb: PatchDB<DataModel> private patchDb: PatchDB<DataModel>
private patchSub: Subscription private patchSub: Subscription
get data () { return this.patchDb.store.cache.data }
constructor ( constructor (
@Inject(PATCH_SOURCE) private readonly source: Source<DataModel>, @Inject(PATCH_SOURCE) private readonly source: Source<DataModel>,
@Inject(PATCH_HTTP) private readonly http: ApiService, @Inject(PATCH_HTTP) private readonly http: ApiService,
@@ -33,7 +34,6 @@ export class PatchDbService {
async init (): Promise<void> { async init (): Promise<void> {
const cache = await this.bootstrapper.init() const cache = await this.bootstrapper.init()
this.patchDb = new PatchDB([this.source, this.http], this.http, cache) this.patchDb = new PatchDB([this.source, this.http], this.http, cache)
this.data = this.patchDb.store.cache.data
} }
start (): void { start (): void {
@@ -44,7 +44,7 @@ export class PatchDbService {
.pipe(debounceTime(500)) .pipe(debounceTime(500))
.subscribe({ .subscribe({
next: cache => { next: cache => {
console.log('saving cacheee: ', cache) console.log('saving cacheee: ', JSON.parse(JSON.stringify(cache)))
this.connectionStatus$.next(ConnectionStatus.Connected) this.connectionStatus$.next(ConnectionStatus.Connected)
this.bootstrapper.update(cache) this.bootstrapper.update(cache)
}, },
@@ -82,8 +82,9 @@ export class PatchDbService {
watch$: Store<DataModel>['watch$'] = (...args: (string | number)[]): Observable<DataModel> => { watch$: Store<DataModel>['watch$'] = (...args: (string | number)[]): Observable<DataModel> => {
console.log('WATCHING', ...args) console.log('WATCHING', ...args)
return this.patchDb.store.watch$(...(args as [])).pipe( return this.patchDb.store.watch$(...(args as []))
tap(cache => console.log('CHANGE IN STORE', cache)), .pipe(
tap(data => console.log('CHANGE IN STORE', data, ...args)),
catchError(e => { catchError(e => {
console.error(e) console.error(e)
return of(e.message) return of(e.message)

View File

@@ -13,7 +13,7 @@ export class ServerConfigService {
constructor ( constructor (
private readonly trackingModalCtrl: TrackingModalController, private readonly trackingModalCtrl: TrackingModalController,
private readonly apiService: ApiService, private readonly embassyApi: ApiService,
private readonly sshService: SSHService, private readonly sshService: SSHService,
) { } ) { }
@@ -35,19 +35,19 @@ export class ServerConfigService {
saveFns: { [key: string]: (val: any) => Promise<any> } = { saveFns: { [key: string]: (val: any) => Promise<any> } = {
autoCheckUpdates: async (value: boolean) => { autoCheckUpdates: async (value: boolean) => {
return this.apiService.setDbValue({ pointer: 'ui/auto-check-updates', value }) return this.embassyApi.setDbValue({ pointer: 'ui/auto-check-updates', value })
}, },
ssh: async (pubkey: string) => { ssh: async (pubkey: string) => {
return this.sshService.add(pubkey) return this.sshService.add(pubkey)
}, },
eosMarketplace: async (enabled: boolean) => { eosMarketplace: async (enabled: boolean) => {
return this.apiService.setEosMarketplace(enabled) return this.embassyApi.setEosMarketplace(enabled)
}, },
// packageMarketplace: async (url: string) => { // packageMarketplace: async (url: string) => {
// return this.apiService.setPackageMarketplace({ url }) // return this.embassyApi.setPackageMarketplace({ url })
// }, // },
// password: async (password: string) => { // password: async (password: string) => {
// return this.apiService.updatePassword({ password }) // return this.embassyApi.updatePassword({ password })
// }, // },
} }
} }

View File

@@ -5,17 +5,21 @@ import { WizardBaker } from '../components/install-wizard/prebaked-wizards'
import { OSWelcomePage } from '../modals/os-welcome/os-welcome.page' import { OSWelcomePage } from '../modals/os-welcome/os-welcome.page'
import { displayEmver } from '../pipes/emver.pipe' import { displayEmver } from '../pipes/emver.pipe'
import { RR } from './api/api.types' import { RR } from './api/api.types'
import { PatchDbService } from './patch-db/patch-db.service'
import { ConfigService } from './config.service' import { ConfigService } from './config.service'
import { Emver } from './emver.service' import { Emver } from './emver.service'
import { MarketplaceService } from '../pages/marketplace-routes/marketplace.service' import { MarketplaceService } from '../pages/marketplace-routes/marketplace.service'
import { MarketplaceApiService } from './api/marketplace/marketplace-api.service' import { MarketplaceApiService } from './api/marketplace/marketplace-api.service'
import { DataModel, PackageDataEntry } from './patch-db/data-model'
import { PatchDbService } from './patch-db/patch-db.service'
import { filter, take } from 'rxjs/operators'
import { isEmptyObject } from '../util/misc.util'
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class StartupAlertsService { export class StartupAlertsService {
private checks: Check<any>[] private checks: Check<any>[]
data: DataModel
constructor ( constructor (
private readonly alertCtrl: AlertController, private readonly alertCtrl: AlertController,
@@ -57,7 +61,14 @@ export class StartupAlertsService {
// Each promise fires more or less concurrently, so each c.check(server) is run concurrently // Each promise fires more or less concurrently, so each c.check(server) is run concurrently
// Then, since we await previousDisplay before c.display(res), each promise executing gets hung awaiting the display of the previous run // Then, since we await previousDisplay before c.display(res), each promise executing gets hung awaiting the display of the previous run
async runChecks (): Promise<void> { async runChecks (): Promise<void> {
await this.checks this.patch.watch$()
.pipe(
filter(data => !isEmptyObject(data)),
take(1),
)
.subscribe(async data => {
this.data = data
await this.checks
.filter(c => !c.hasRun && c.shouldRun()) .filter(c => !c.hasRun && c.shouldRun())
// returning true in the below block means to continue to next modal // returning true in the below block means to continue to next modal
// returning false means to skip all subsequent modals // returning false means to skip all subsequent modals
@@ -76,18 +87,19 @@ export class StartupAlertsService {
if (!checkRes) return true if (!checkRes) return true
if (displayRes) return c.display(checkRes) if (displayRes) return c.display(checkRes)
}, Promise.resolve(true)) }, Promise.resolve(true))
})
} }
private shouldRunOsWelcome (): boolean { private shouldRunOsWelcome (): boolean {
return this.patch.data.ui['welcome-ack'] !== this.config.version return this.data.ui['welcome-ack'] !== this.config.version
} }
private shouldRunOsUpdateCheck (): boolean { private shouldRunOsUpdateCheck (): boolean {
return this.patch.data.ui['auto-check-updates'] return this.data.ui['auto-check-updates']
} }
private shouldRunAppsCheck (): boolean { private shouldRunAppsCheck (): boolean {
return this.patch.data.ui['auto-check-updates'] return this.data.ui['auto-check-updates']
} }
private async osUpdateCheck (): Promise<RR.GetMarketplaceEOSRes | undefined> { private async osUpdateCheck (): Promise<RR.GetMarketplaceEOSRes | undefined> {
@@ -101,8 +113,8 @@ export class StartupAlertsService {
} }
private async appsCheck (): Promise<boolean> { private async appsCheck (): Promise<boolean> {
const updates = await this.marketplaceService.getUpdates(this.patch.data['package-data']) await this.marketplaceService.getUpdates(this.data['package-data'])
return !!updates.length return !!this.marketplaceService.updates.length
} }
private async displayOsWelcome (): Promise<boolean> { private async displayOsWelcome (): Promise<boolean> {