Newer
Older
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
import { distinctUntilChanged, map, take, tap } from 'rxjs/operators';
import { of, timer, zip } from 'rxjs';
import * as postMessage from '../utils/postMessage';
// TODO This is not working
// api.on('connected', () => ...);
// api.on('disconnected', () => ...);
// So instead, we poll every 1s
map(_ => Boolean(this.api && this.api.isConnected)),
// Request WS port and interface from electron
postMessage.send('WS_INTERFACE_REQUEST');
postMessage.send('WS_PORT_REQUEST');
const lsToken = store.get(LS_KEY);
const token$ = lsToken
? of(lsToken).pipe(tap(() => debug('Got token from localStorage.')))
: this.requestNewToken$();
zip(
token$,
postMessage.listen$('WS_INTERFACE_RESPONSE'),
postMessage.listen$('WS_PORT_RESPONSE')
)
.pipe(take(1))
.subscribe(([token, wsInterface, wsPort]) =>
this.connectToApi(token, wsInterface, wsPort)
connectToApi (token, wsInterface, wsPort) {
// Get the provider, optionally from --ws-interface and --ws-port flags
let provider = `ws://${wsInterface}:${wsPort}`;
// FIXME - change to WsSecure when implement `wss` and security certificates
token.replace(/[^a-zA-Z0-9]/g, '') // Sanitize token
)
);
// Initialize the light.js lib
light.setApi(api);
// Also set api as member for React Components to use it if needed
this.api = api;
}
requestNewToken$ () {
postMessage.send('SIGNER_NEW_TOKEN_REQUEST');
return postMessage.listen$('SIGNER_NEW_TOKEN_RESPONSE').pipe(
tap(() => debug('Successfully received new token.')),
tap(this.updateLS)
);
}
updateLS = token => {
store.set(LS_KEY, token);