-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhsync-web.js
71 lines (57 loc) · 1.8 KB
/
hsync-web.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const mqtt = require('precompiled-mqtt');
const buffer = require('buffer');
const net = require('net-web');
const { createHsync, setNet, setMqtt } = require('./connection');
const { setRTC } = require('./lib/peers');
const rtc = require('./lib/rtc-web');
const config = require('./config');
// TODO need to make this work with web/service workers
window.Buffer = buffer.Buffer;
setRTC(rtc);
setNet(net);
setMqtt(mqtt);
async function dynamicConnect(configObj = { useLocalStorage: true }) {
const fullConfig = {...config, ...configObj};
fullConfig.dynamicHost = fullConfig.dynamicHost || fullConfig.defaultDynamicHost;
if (fullConfig.net) {
setNet(fullConfig.net);
}
let con;
if (configObj.useLocalStorage) {
const localConfigStr = localStorage.getItem('hsyncConfig');
if (localConfigStr) {
const localConfig = JSON.parse(localConfigStr);
if ((Date.now() - localConfig.created) < (localConfig.timeout * 0.66)) {
fullConfig.hsyncSecret = localConfig.hsyncSecret;
fullConfig.hsyncServer = localConfig.hsyncServer;
} else {
localStorage.removeItem('hsyncConfig');
}
}
con = await createHsync(fullConfig);
if (!fullConfig.hsyncSecret) {
const storeConfig = {
hsyncSecret: con.hsyncSecret,
hsyncServer: con.hsyncServer,
timeout: con.dynamicTimeout,
created: Date.now(),
};
localStorage.setItem('hsyncConfig', JSON.stringify(storeConfig));
}
return con;
}
con = await createHsync(fullConfig);
return con;
}
function createConnection(configObj = {}) {
const fullConfig = {...config, ...configObj};
return createHsync(fullConfig);
}
const hsync = globalThis.hsync || {
createConnection,
dynamicConnect,
net,
config,
};
globalThis.hsync = hsync;
module.exports = hsync;