Newer
Older
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
import isElectron from 'is-electron';
import light from '@parity/light.js';
import { distinctUntilChanged, map } from 'rxjs/operators';
const electron = isElectron() ? window.require('electron') : null;
// TODO This is not working
// api.on('connected', () => ...);
// api.on('disconnected', () => ...);
// So instead, we poll every 1s
map(_ => Boolean(this.api && this.api.isConnected)),
// Retrieve token from localStorage
const token = store.get(LS_KEY);
if (token) {
Luke Schoen
committed
// FIXME - consider moving to start of this constructor block since
// if `setToken` method is called then `connectToApi` is called, which
// requires `electron` to be defined
'Not in Electron, ParityStore will only have limited capabilities.'
);
return;
}
const { ipcRenderer, remote } = electron;
// Check if isParityRunning
this.setIsParityRunning(!!remote.getGlobal('isParityRunning'));
// We also listen to future changes
ipcRenderer.on('parity-running', (_, isParityRunning) => {
this.setIsParityRunning(isParityRunning);
});
}
connectToApi = () => {
// Get the provider, optionally from --ws-interface and --ws-port flags
const [defaultInterface, defaultPort] = ['127.0.0.1', '8546'];
let provider = `ws://${defaultInterface}:${defaultPort}`;
if (electron) {
const { remote } = electron;
const wsInterface = remote.getGlobal('wsInterface');
const wsPort = remote.getGlobal('wsPort');
provider = `ws://${wsInterface || defaultInterface}:${wsPort ||
defaultPort}`;
const api = new Api(
new Api.Provider.Ws(
provider,
this.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 = () => {
const { ipcRenderer } = electron;
// Request new token from Electron
ipcRenderer.send('asynchronous-message', 'signer-new-token');
ipcRenderer.once('signer-new-token-reply', (_, token) => {
if (!token) {
return;
}
// If `parity signer new-token` has successfully given us a token back,
// then we submit it
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
this.setToken(token);
});
};
@action
setIsParityRunning = isParityRunning => {
if (isParityRunning === this.isParityRunning) {
return;
}
this.isParityRunning = isParityRunning;
// Request new token if parity's running but we still don't have a token
if (isParityRunning && !this.token) {
this.requestNewToken();
}
};
@action
setToken = token => {
if (token === this.token) {
return;
}
this.token = token;
// If we receive a new token, then we try to connect to the Api with this
// new token
this.connectToApi();
this.updateLS();
};
updateLS = () => store.set(LS_KEY, this.token);
}
export default new ParityStore();