-
Notifications
You must be signed in to change notification settings - Fork 325
/
Copy pathstore.js
257 lines (236 loc) · 9 KB
/
store.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
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
'use strict'
/* eslint-env browser, webextensions */
import browser from 'webextension-polyfill'
import isIPFS from 'is-ipfs'
import { browserActionFilesCpImportCurrentTab } from '../../lib/ipfs-import.js'
import { ipfsContentPath } from '../../lib/ipfs-path.js'
import { welcomePage, optionsPage } from '../../lib/constants.js'
import { contextMenuViewOnGateway, contextMenuCopyAddressAtPublicGw, contextMenuCopyPermalink, contextMenuCopyRawCid, contextMenuCopyCanonicalAddress, contextMenuCopyCidAddress } from '../../lib/context-menus.js'
import { endSession, handleConsentFromState, startSession, trackView } from '../../lib/telemetry.js'
// The store contains and mutates the state for the app
export default (state, emitter) => {
Object.assign(state, {
// Global toggles
active: true,
redirect: true,
// UI contexts
isIpfsContext: false, // Active Tab represents IPFS resource
isRedirectContext: false, // Active Tab or its subresources could be redirected
// IPFS details
ipfsNodeType: 'external',
isIpfsOnline: false,
ipfsApiUrl: null,
publicGatewayUrl: null,
publicSubdomainGatewayUrl: null,
gatewayAddress: null,
swarmPeers: null,
gatewayVersion: null,
isApiAvailable: false,
// isRedirectContext
currentTab: null,
currentFqdn: null,
currentDnslinkFqdn: null,
enabledOn: [],
disabledOn: []
})
let port
emitter.on('DOMContentLoaded', async () => {
handleConsentFromState(state)
trackView('browser-action')
// initial render with status stub
emitter.emit('render')
// initialize connection to the background script which will trigger UI updates
port = browser.runtime.connect({ name: 'browser-action-port' })
port.onMessage.addListener(async (message) => {
if (message.statusUpdate) {
const status = message.statusUpdate
console.log('In browser action, received message from background:', message)
await updateBrowserActionState(status)
emitter.emit('render')
}
})
// fix for https://github.com/ipfs-shipyard/ipfs-companion/issues/318
setTimeout(() => {
document.body.style.height = window.innerHeight + 1 + 'px'
setTimeout(() => document.body.style.removeProperty('height'), 50)
}, 100)
})
emitter.on('viewOnGateway', async () => {
port.postMessage({ event: contextMenuViewOnGateway })
window.close()
})
emitter.on('copy', function (copyAction) {
switch (copyAction) {
case contextMenuCopyCanonicalAddress:
port.postMessage({ event: contextMenuCopyCanonicalAddress })
break
case contextMenuCopyCidAddress:
port.postMessage({ event: contextMenuCopyCidAddress })
break
case contextMenuCopyRawCid:
port.postMessage({ event: contextMenuCopyRawCid })
break
case contextMenuCopyAddressAtPublicGw:
port.postMessage({ event: contextMenuCopyAddressAtPublicGw })
break
case contextMenuCopyPermalink:
port.postMessage({ event: contextMenuCopyPermalink })
break
}
window.close()
})
emitter.on('filesCpImport', () => {
port.postMessage({ event: browserActionFilesCpImportCurrentTab })
window.close()
})
emitter.on('quickImport', () => {
browser.tabs.create({ url: browser.runtime.getURL('dist/popup/quick-import.html') })
window.close()
})
emitter.on('openWelcomePage', async () => {
try {
await browser.tabs.create({ url: welcomePage })
window.close()
} catch (error) {
console.error(`Unable Open WelcomePage (${welcomePage})`, error)
}
})
emitter.on('openWebUi', async (page = '/') => {
const url = `${state.webuiRootUrl}#${page}`
try {
await browser.tabs.create({ url })
window.close()
} catch (error) {
console.error(`Unable Open Web UI (${url})`, error)
}
})
emitter.on('openReleaseNotes', async () => {
const { version } = browser.runtime.getManifest()
const stableChannel = version.match(/\./g).length === 2
let url
try {
if (stableChannel) {
url = `https://github.com/ipfs-shipyard/ipfs-companion/releases/tag/v${version}`
await browser.storage.local.set({ dismissedUpdate: version })
} else {
// swap URL and do not dismiss
url = 'https://github.com/ipfs-shipyard/ipfs-companion/issues/964'
}
// Note: opening tab needs to happen after storage.local.set because in Chromium 86
// it triggers a premature window.close, which aborts storage update
await browser.tabs.create({ url })
window.close()
} catch (error) {
console.error(`Unable to open release notes (${url})`, error)
}
})
emitter.on('openPrefs', () => {
browser.runtime.openOptionsPage()
.then(() => window.close())
.catch((err) => {
console.error('runtime.openOptionsPage() failed, opening options page in tab instead.', err)
// brave: fallback to opening options page as a tab.
browser.tabs.create({ url: browser.runtime.getURL(optionsPage) })
})
})
emitter.on('toggleGlobalRedirect', async () => {
const redirectEnabled = state.redirect
state.redirect = !redirectEnabled
state.gatewayAddress = state.redirect ? state.gwURLString : state.pubGwURLString
emitter.emit('render')
try {
await browser.storage.local.set({ useCustomGateway: !redirectEnabled })
} catch (error) {
console.error(`Unable to update redirect state due to ${error}`)
state.redirect = redirectEnabled
emitter.emit('render')
}
})
emitter.on('toggleSiteIntegrations', async () => {
const wasOptedOut = state.currentTabIntegrationsOptOut
state.currentTabIntegrationsOptOut = !wasOptedOut
emitter.emit('render')
try {
let { enabledOn, disabledOn, currentTab, currentDnslinkFqdn, currentFqdn } = state
// if we are on /ipns/fqdn.tld/ then use hostname from DNSLink
const fqdn = currentDnslinkFqdn || currentFqdn
if (wasOptedOut) {
disabledOn = disabledOn.filter(host => host !== fqdn)
enabledOn.push(fqdn)
} else {
enabledOn = enabledOn.filter(host => host !== fqdn)
disabledOn.push(fqdn)
}
// console.dir('toggleSiteIntegrations', state)
await browser.storage.local.set({ disabledOn, enabledOn })
const path = ipfsContentPath(currentTab.url, { keepURIParams: true })
// Reload the current tab to apply updated redirect preference
if (!currentDnslinkFqdn || !isIPFS.ipnsPath(path)) {
// No DNSLink, reload URL as-is
await browser.tabs.reload(currentTab.id)
} else {
// DNSLinked websites require URL change
// from http?://gateway.tld/ipns/{fqdn}/some/path OR
// from http?://{fqdn}.ipns.gateway.tld/some/path
// to http://{fqdn}/some/path
// (defaulting to http: https websites will have HSTS or a redirect)
const originalUrl = path.replace(/^.*\/ipns\//, 'http://')
await browser.tabs.update(currentTab.id, {
// FF only: loadReplace: true,
url: originalUrl
})
}
} catch (error) {
console.error(`Unable to update integrations state due to ${error}`)
emitter.emit('render')
}
})
emitter.on('toggleActive', async () => {
const prev = state.active
state.active = !prev
if (!state.active) {
endSession()
state.gatewayAddress = state.pubGwURLString
state.ipfsApiUrl = null
state.gatewayVersion = null
state.swarmPeers = null
state.isIpfsOnline = false
}
try {
await browser.storage.local.set({ active: state.active })
startSession()
handleConsentFromState(state)
} catch (error) {
console.error(`Unable to update global Active flag due to ${error}`)
state.active = prev
}
emitter.emit('render')
})
async function updateBrowserActionState (status) {
if (status) {
// Copy all attributes
Object.assign(state, status)
if (state.active && status.redirect && (status.ipfsNodeType !== 'embedded')) {
state.gatewayAddress = status.gwURLString
} else {
state.gatewayAddress = status.pubGwURLString
}
// Import requires access to the background page (https://github.com/ipfs-shipyard/ipfs-companion/issues/477)
state.isApiAvailable = state.active && !!(await getBackgroundPage()) && !browser.extension.inIncognitoContext // https://github.com/ipfs-shipyard/ipfs-companion/issues/243
state.swarmPeers = !state.active || status.peerCount === -1 ? null : status.peerCount
state.isIpfsOnline = state.active && status.peerCount > -1
state.gatewayVersion = state.active && status.gatewayVersion ? status.gatewayVersion : null
state.ipfsApiUrl = state.active ? status.apiURLString : null
} else {
state.ipfsNodeType = 'external'
state.swarmPeers = null
state.isIpfsOnline = false
state.gatewayVersion = null
state.isIpfsContext = false
state.isRedirectContext = false
}
}
}
function getBackgroundPage () {
return browser.runtime.getBackgroundPage()
}