-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathindex.ts
More file actions
230 lines (191 loc) · 6.31 KB
/
index.ts
File metadata and controls
230 lines (191 loc) · 6.31 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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import path from 'path'
import { Readable } from 'stream'
import { hash } from 'eth-ens-namehash'
import log from 'electron-log'
import crypto from 'crypto'
import tar from 'tar-fs'
import store from '../store'
import nebulaApi from '../nebula'
import server from './server'
import extractColors from '../windows/extractColors'
import { dappPathExists, getDappCacheDir, isDappVerified } from './verify'
import type { Dapp } from '../store/state/types'
const nebula = nebulaApi()
class DappStream extends Readable {
constructor(hash: string) {
super()
this.start(hash)
}
async start(hash: string) {
for await (const buf of nebula.ipfs.get(hash, { archive: true })) {
this.push(buf)
}
this.push(null)
}
_read() {
// empty
}
}
function getDapp(dappId: string): Dapp {
return store('main.dapps', dappId)
}
async function getDappColors(dappId: string) {
const dapp = getDapp(dappId)
const session = crypto.randomBytes(6).toString('hex')
server.sessions.add(dapp.ens, session)
const url = `http://${dapp.ens}.localhost:8421/?session=${session}`
try {
const colors = await extractColors(url, dapp.ens)
store.updateDapp(dappId, { colors })
server.sessions.remove(dapp.ens, session)
} catch (e) {
log.error(e)
}
}
const createTarStream = (dappId: string) => {
return tar.extract(getDappCacheDir(), {
map: (header) => ({ ...header, name: path.join(dappId, ...header.name.split('/').slice(1)) })
})
}
const writeDapp = async (dappId: string, hash: string) => {
return new Promise<void>((resolve, reject) => {
try {
const dapp = new DappStream(hash)
const tarStream = createTarStream(dappId)
tarStream.on('error', reject)
tarStream.on('finish', resolve)
dapp.pipe(tarStream)
} catch (e) {
reject(e)
}
})
}
const cacheDapp = async (dappId: string, hash: string) => {
await writeDapp(dappId, hash)
await getDappColors(dappId)
return dappId
}
// TODO: change to correct manifest type one Nebula version with types are published
async function updateDappContent(dappId: string, manifest: any) {
try {
// Create a local cache of the content
await cacheDapp(dappId, manifest.content)
store.updateDapp(dappId, { content: manifest.content, manifest })
} catch (e) {
log.error('error updating dapp cache', e)
}
}
let retryTimer: NodeJS.Timeout
// Takes dappId and checks if the dapp is up to date
async function checkStatus(dappId: string) {
clearTimeout(retryTimer)
const dapp = store('main.dapps', dappId) as Dapp
const { checkStatusRetryCount, openWhenReady } = dapp
try {
const { record, manifest } = await nebula.resolve(dapp.ens)
const { version, content } = manifest || {}
if (!content) {
log.error(
`Attempted load dapp with id ${dappId} (${dapp.ens}) but manifest contained no content`,
manifest
)
return
}
log.info(`Resolved content for ${dapp.ens}, version: ${version || 'unknown'}`)
store.updateDapp(dappId, { record })
const isDappCurrent = async () => {
return (
dapp.content === content && (await dappPathExists(dappId)) && (await isDappVerified(dappId, content))
)
}
// Checks if all assets are up to date with current manifest
if (!(await isDappCurrent())) {
log.info(`Updating content for dapp ${dappId} from hash ${content}`)
// Sets status to 'updating' when updating the bundle
store.updateDapp(dappId, { status: 'updating' })
// Update dapp assets
await updateDappContent(dappId, manifest)
} else {
log.info(`Dapp ${dapp.ens} already up to date: ${content}`)
}
// Sets status to 'ready' when done
store.updateDapp(dappId, { status: 'ready', openWhenReady: false })
// The frame id 'dappLauncher' needs to refrence target frame
if (openWhenReady) surface.open('dappLauncher', dapp.ens)
} catch (e) {
log.error('Check status error', e)
const retry = checkStatusRetryCount || 0
if (retry < 4) {
retryTimer = setTimeout(() => {
store.updateDapp(dappId, { status: 'initial', checkStatusRetryCount: retry + 1 })
}, 1000)
} else {
store.updateDapp(dappId, { status: 'failed', checkStatusRetryCount: 0 })
}
}
}
const refreshDapps = ({ statusFilter = '' } = {}) => {
const dapps = store('main.dapps')
Object.keys(dapps || {})
.filter((id) => !statusFilter || dapps[id].status === statusFilter)
.forEach((id) => {
store.updateDapp(id, { status: 'loading' })
if (nebula.ready()) {
checkStatus(id)
} else {
nebula.once('ready', () => checkStatus(id))
}
})
}
const checkNewDapps = () => refreshDapps({ statusFilter: 'initial' })
// Check all dapps on startup
refreshDapps()
// Check all dapps every hour
setInterval(() => refreshDapps(), 1000 * 60 * 60)
// Check any new dapps that are added
store.observer(checkNewDapps)
let nextId = 0
const getId = () => (++nextId).toString()
const surface = {
manifest: (_ens: string) => {
// gets the dapp manifest and returns all options and details for user to confirm before installing
},
add: (dapp: Dapp) => {
const { ens, config } = dapp
const id = hash(ens)
const status = 'initial'
const existingDapp = store('main.dapps', id)
// If ens name has not been installed, start install
if (!existingDapp) store.appDapp({ id, ens, status, config, manifest: {}, current: {} })
},
addServerSession(_namehash: string /* , session */) {
// server.sessions.add(namehash, session)
},
unsetCurrentView(frameId: string) {
store.setCurrentFrameView(frameId, '')
},
open(frameId: string, ens: string) {
const session = crypto.randomBytes(6).toString('hex')
const dappId = hash(ens)
const dapp = store('main.dapps', dappId)
if (dapp.status === 'ready') {
const url = `http://${ens}.localhost:8421/?session=${session}`
const view = {
id: getId(),
ready: false,
dappId,
ens,
url
}
server.sessions.add(ens, session)
if (store('main.frames', frameId)) {
store.addFrameView(frameId, view)
} else {
log.warn(`Attempted to open frame "${frameId}" for ${ens} but frame does not exist`)
}
} else {
store.updateDapp(dappId, { ens, status: 'initial', openWhenReady: true })
}
}
}
export default surface