1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-29 15:50:28 +01:00
metamask-extension/app/scripts/lib/ens-ipfs/setup.js

62 lines
2.0 KiB
JavaScript
Raw Normal View History

const urlUtil = require('url')
const extension = require('extensionizer')
const resolveEnsToIpfsContentId = require('./resolver.js')
const supportedTopLevelDomains = ['eth']
module.exports = setupEnsIpfsResolver
function setupEnsIpfsResolver ({ provider }) {
// install listener
const urlPatterns = supportedTopLevelDomains.map(tld => `*://*.${tld}/*`)
extension.webRequest.onErrorOccurred.addListener(webRequestDidFail, { urls: urlPatterns })
// return api object
return {
// uninstall listener
remove () {
extension.webRequest.onErrorOccurred.removeListener(webRequestDidFail)
},
}
async function webRequestDidFail (details) {
const { tabId, url } = details
// ignore requests that are not associated with tabs
if (tabId === -1) return
// parse ens name
const urlData = urlUtil.parse(url)
const { hostname: name, path, search } = urlData
const domainParts = name.split('.')
const topLevelDomain = domainParts[domainParts.length - 1]
// if unsupported TLD, abort
if (!supportedTopLevelDomains.includes(topLevelDomain)) return
// otherwise attempt resolve
attemptResolve({ tabId, name, path, search })
}
async function attemptResolve ({ tabId, name, path, search }) {
extension.tabs.update(tabId, { url: `loading.html` })
2019-05-04 18:57:19 +02:00
let url = `https://manager.ens.domains/name/${name}`
try {
2019-04-04 17:15:57 +02:00
const {type, hash} = await resolveEnsToIpfsContentId({ provider, name })
if (type === 'ipfs-ns') {
2019-05-04 18:57:19 +02:00
const resolvedUrl = `https://gateway.ipfs.io/ipfs/${hash}${path}${search || ''}`
2019-04-04 17:15:57 +02:00
try {
// check if ipfs gateway has result
2019-05-04 18:57:19 +02:00
const response = await fetch(resolvedUrl, { method: 'HEAD' })
if (response.status === 200) url = resolvedUrl
2019-04-04 17:15:57 +02:00
} catch (err) {
console.warn(err)
}
2019-04-04 17:15:57 +02:00
} else if (type === 'swarm-ns') {
url = `https://swarm-gateways.net/bzz:/${hash}${path}${search || ''}`
}
} catch (err) {
console.warn(err)
2019-05-04 18:57:19 +02:00
} finally {
extension.tabs.update(tabId, { url })
}
}
}