-
Notifications
You must be signed in to change notification settings - Fork 4
/
swarm.js
110 lines (91 loc) · 2.41 KB
/
swarm.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import Saga from '@geut/saga';
import config from './config';
import ram from 'random-access-memory';
import swarm from '@geut/discovery-swarm-webrtc';
import signalhub from 'signalhubws';
import React, { Component } from 'react';
// P2P DEFAULTS
const webrtcOpts = {
config: {
iceServers: (process.env.ICE_URLS || config.ICE_URLS)
.split(';')
.map(data => {
const [urls, credential, username] = data.split(',');
if (credential && username) {
return {
urls,
credential,
username
};
}
return { urls };
})
}
};
// END P2P DEFAULTS
const initComm = async (username, key) => {
const publicKey = key && key.length > 0 ? key : null;
const saga = Saga(ram, publicKey, username);
await saga.initialize();
const sw = swarm({
id: username,
stream: () => {
return saga.replicate();
}
});
const discoveryKey = saga.db.discoveryKey.toString('hex');
const signalUrls = (process.env.SIGNAL_URLS || config.SIGNAL_URLS).split(';');
sw.join(signalhub(discoveryKey, signalUrls), webrtcOpts);
sw.on('connection', async peer => {
try {
await saga.connect(peer);
} catch (err) {
console.log(err);
}
});
return saga;
};
export default initComm;
const SwarmContext = React.createContext(null);
class SwarmProvider extends Component {
state = {
swarmReady: false
};
async componentDidMount() {
const { username, match: { params: { draftId = null } } = {} } = this.props;
const swarm = await initComm(username, draftId);
this.setState({
swarm,
swarmReady: true,
hasDraftId: !!draftId
});
}
render() {
const { swarmReady, swarm, hasDraftId } = this.state;
const { children } = this.props;
return swarmReady ? (
<SwarmContext.Provider value={{ swarm, hasDraftId }}>
{children}
</SwarmContext.Provider>
) : null;
}
}
const withSwarm = WrappedComponent => {
return class extends Component {
static displayName = `WithSwarm${WrappedComponent.displayName}`;
render() {
return (
<SwarmContext.Consumer>
{({ swarm, hasDraftId }) => (
<WrappedComponent
{...this.props}
swarm={swarm}
hasDraftId={hasDraftId}
/>
)}
</SwarmContext.Consumer>
);
}
};
};
export { SwarmProvider, withSwarm };