aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/ipfsContent.js
blob: a6b99b2f9b1016f1f0025ce20e816c4858dd535c (plain) (blame)
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
const extension = require('extensionizer')
const resolver = require('./resolver.js')

module.exports = function (provider) {
    extension.webRequest.onBeforeRequest.addListener(details => {
        const urlhttpreplace = details.url.replace(/\w+?:\/\//, '')
        const url = urlhttpreplace.replace(/[\\/].*/g, '') // eslint-disable-line no-useless-escape
        let domainhtml = urlhttpreplace.match(/[\\/].*/g) // eslint-disable-line no-useless-escape
        let clearTime = null
        const name = url.replace(/\/$/g, '')
        if (domainhtml === null) domainhtml = ['']
        extension.tabs.getSelected(null, tab => {
            extension.tabs.update(tab.id, { url: 'loading.html' })

            clearTime = setTimeout(() => {
                return extension.tabs.update(tab.id, { url: '404.html' })
            }, 60000)

            resolver.resolve(name, provider).then(ipfsHash => {
                clearTimeout(clearTime)
                let url = 'https://ipfs.infura.io/ipfs/' + ipfsHash + domainhtml[0]
                return fetch(url, { method: 'HEAD' }).then(response => response.status).then(statusCode => {
                    if (statusCode !== 200) return extension.tabs.update(tab.id, { url: '404.html' })
                    extension.tabs.update(tab.id, { url: url })
                })
                .catch(err => {
                    url = 'https://ipfs.infura.io/ipfs/' + ipfsHash + domainhtml[0]
                    extension.tabs.update(tab.id, {url: url})
                    return err
                })
            })
            .catch(err => {
                clearTimeout(clearTime)
                const url = err === 'unsupport' ? 'unsupport' : 'error'
                extension.tabs.update(tab.id, {url: `${url}.html?name=${name}`})
            })
        })
        return { cancel: true }
    }, {urls: ['*://*.eth/', '*://*.eth/*']})
}