-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstore.js
More file actions
106 lines (86 loc) · 2.53 KB
/
Copy pathstore.js
File metadata and controls
106 lines (86 loc) · 2.53 KB
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
'use strict'
const getIpfs = require('window.ipfs-fallback')
const TOPIC = 'chat'
function createChatStore () {
return function chatStore (state, emitter) {
let ipfs
state.id = null
state.name = window.localStorage.getItem('name') || 'anonymous coward'
state.text = ''
state.messages = []
state.posting = false
state.subscribed = false
state.error = null
const onMessage = (msg) => {
msg = Object.assign({}, msg)
const exists = state.messages.some(m => m.seqno.equals(Buffer.from(msg.seqno)))
if (exists) return
try {
msg.seqno = Buffer.from(msg.seqno)
msg.data = JSON.parse(msg.data)
} catch (err) {
return console.warn('Invalid message data', err)
}
state.messages = [msg].concat(state.messages).slice(0, 1000)
emitter.emit('render')
}
emitter.on('DOMContentLoaded', async () => {
ipfs = await getIpfs({
permissions: ['id', 'pubsub.publish', 'pubsub.subscribe'],
ipfs: {
config: {
Addresses: {
Swarm: [
'/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star'
]
}
},
EXPERIMENTAL: {
pubsub: true
}
}
})
try {
await ipfs.pubsub.subscribe(TOPIC, onMessage)
state.subscribed = true
} catch (err) {
console.error('Failed to subscribe', err)
state.subscribed = false
state.error = err
}
try {
state.id = await ipfs.id()
} catch (err) {
console.error('Failed to get node ID', err)
state.error = err
}
emitter.emit('render')
})
emitter.on('nameChange', (name) => {
window.localStorage.setItem('name', name)
state.name = name
emitter.emit('render')
})
emitter.on('textChange', (text) => {
state.text = text
emitter.emit('render')
})
emitter.on('postMessage', async () => {
if (!state.subscribed || !state.text) return
state.posting = true
emitter.emit('render')
try {
const { name, text } = state
await ipfs.pubsub.publish(TOPIC, Buffer.from(JSON.stringify({ name, text })))
state.text = ''
} catch (err) {
console.error('Failed to publish', err)
state.error = err
}
state.posting = false
emitter.emit('render')
})
window.addEventListener('unload', () => ipfs.pubsub.unsubscribe(TOPIC, onMessage))
}
}
module.exports = createChatStore