-
Notifications
You must be signed in to change notification settings - Fork 0
/
room.js
134 lines (105 loc) · 2.99 KB
/
room.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import signal from 'pico-signals';
import nanoid from 'nanoid';
import { omit } from 'lodash';
import createPubsubRoom from 'ipfs-pubsub-room';
import userStore from './user';
let pubsubRoom;
const onChange = signal();
let state = {
messages: [],
peers: {},
peersCount: 0,
};
export const configure = async (params) => {
pubsubRoom = createPubsubRoom(params.ipfs, 'IDM_CHAT_APP');
pubsubRoom
.on('subscribed', () => {
console.log('Now connected!');
const peers = pubsubRoom.getPeers();
state = {
...state,
peers: peers.reduce((acc, peerId) => {
acc[peerId] = null;
return acc;
}, {}),
peersCount: peers.length,
};
onChange.dispatch(state);
})
.on('peer joined', (peerId) => {
console.log('Peer joined:', peerId);
state = {
...state,
peers: {
...state.peers,
[peerId]: null,
},
peersCount: state.peersCount + 1,
};
onChange.dispatch(state);
})
.on('peer left', (peerId) => {
console.log('Peer left:', peerId);
state = {
...state,
peers: omit(state.peers, peerId),
peersCount: state.peersCount - 1,
};
onChange.dispatch(state);
})
.on('message', ({ data }) => {
const dataStr = new TextDecoder().decode(data);
const dataJson = JSON.parse(dataStr);
console.log('New message:', dataJson);
switch (dataJson.type) {
case 'NEW_MESSAGE':
state = {
...state,
messages: [
...state.messages,
dataJson.message,
],
};
onChange.dispatch(state);
break;
default:
console.warn('Unknown message', dataJson);
}
});
};
const store = {
get state() {
return state;
},
sendMessage: async (text) => {
const { currentUser } = userStore.state;
// Skip if we are logged out or text message is empty
if (!currentUser || !text.trim().length) {
return;
}
const message = {
id: nanoid(),
author: currentUser,
text,
timestamp: Date.now(),
};
message.signature = {};
console.log('Sending message:', message);
pubsubRoom.broadcast(JSON.stringify({
type: 'NEW_MESSAGE',
message,
}));
},
verifyMessage: async (message) => {
const { signature, ...originalMessage } = message;
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = {
valid: false,
error: new Error('This is a dummy signature'),
};
console.log('Verification result:', result);
return result;
},
subscribe: (fn) => onChange.add(fn),
};
export default store;