import { hexToString } from '../infrastructure/hex_encoding' ; import * as server from '../model/server' ; import { ShadowboxServer } from './shadowbox_server' ; class ManualServer extends ShadowboxServer implements server . ManualServer { constructor ( id , private manualServerConfig , private forgetCallback ) { super ( id ) ; this . setManagementApiUrl ( manualServerConfig . apiUrl ) ; try { trustCertificate ( btoa ( hexToString ( manualServerConfig . certSha256 ) ) ) ; } catch ( e ) { console . error ( 'Error trusting certificate' ) ; } } getCertificateFingerprint ( ) { return this . manualServerConfig . certSha256 ; } forget ( ) { this . forgetCallback ( ) ; } } export class ManualServerRepository implements server . ManualServerRepository { private servers : server . ManualServer [ ] = [ ] ; constructor ( private storageKey ) { this . loadServers ( ) ; } addServer ( config ) { const existingServer = this . findServer ( config ) ; if ( ! ! existingServer ) { console . debug ( 'server already added' ) ; return Promise . resolve ( existingServer ) ; } const server = this . createServer ( config ) ; this . servers . push ( server ) ; this . storeServers ( ) ; return Promise . resolve ( server ) ; } listServers ( ) { return Promise . resolve ( this . servers ) ; } findServer ( config ) { return this . servers . find ( server => server . getManagementApiUrl ( ) === config . apiUrl ) ; } private loadServers ( ) { this . servers = [ ] ; const serversJson = localStorage . getItem ( this . storageKey ) ; if ( serversJson ) { try { const serverConfigs = JSON . parse ( serversJson ) ; this . servers = serverConfigs . map ( ( config ) => { return this . createServer ( config ) ; } ) ; } catch ( e ) { console . error ( 'Error creating manual servers from localStorage' ) ; } } } private storeServers ( ) { const serverConfigs = this . servers . map ( ( server ) => { return { apiUrl : server . getManagementApiUrl ( ) , certSha256 : server . getCertificateFingerprint ( ) } ; } ) ; localStorage . setItem ( this . storageKey , JSON . stringify ( serverConfigs ) ) ; } private createServer ( config ) { const server = new ManualServer ( `manual:${ config . apiUrl }` , config , ( ) => { this . forgetServer ( server ) ; } ) ; return server ; } private forgetServer ( serverToForget ) { const apiUrl = serverToForget . getManagementApiUrl ( ) ; this . servers = this . servers . filter ( ( server ) => { return apiUrl !== server . getManagementApiUrl ( ) ; } ) ; this . storeServers ( ) ; } }