Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ask ipfs.config for gateway address where possible #309

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions add-on/src/lib/ipfs-companion.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ async function init () {
try {
const options = await browser.storage.local.get(optionDefaults)
ipfs = initIpfsApi(options.ipfsApiUrl)
// If user hasn't provided a custom gateway url, ask ipfs.
if (options.customGatewayUrl === optionDefaults.customGatewayUrl) {
const gatewayUrl = await getGatewayUrl(ipfs)
if (gatewayUrl) {
// use the gateway url as reported by ipfs.config if possible.
options.customGatewayUrl = gatewayUrl
}
}
initStates(options)
registerListeners()
setApiStatusUpdateInterval(options.ipfsApiPollMs)
Expand All @@ -28,6 +36,33 @@ function initIpfsApi (ipfsApiUrl) {
return window.IpfsApi({host: url.hostname, port: url.port, procotol: url.protocol})
}

async function getIpfsConfig (ipfs) {
try {
const buff = await ipfs.config.get()
return JSON.parse(buff.toString())
} catch (err) {
console.log('Failed to get IPFS config', err)
return null
}
}

async function getGatewayUrl (ipfs) {
const config = await getIpfsConfig(ipfs)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you just fetch the Addresses.Gateway value?

$ ipfs config 'Addresses.Gateway'
/ip4/127.0.0.1/tcp/8080

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure can. I thought that getting the entire ipfs config might provide other useful info. Perhaps we won't ever need it, but I don't think it's a bad gamble.

if (!config) return null
return toGatewayUrl(config)
}

function toGatewayUrl (ipfsConfig) {
if (!ipfsConfig || !ipfsConfig.Addresses || !ipfsConfig.Addresses.Gateway) {
return null
}
// there has got to be a better way.
const multiAddrRE = /\/ip4\/(.+)\/tcp\/(\d+)/
const res = multiAddrRE.exec(ipfsConfig.Addresses.Gateway)
if (!res) return null
return `http://${res[1]}:${res[2]}`
}

function initStates (options) {
// we store the most used values in optimized form
// to minimize performance impact on overall browsing experience
Expand Down