liquid-funding/app/utils/ipfs.js

56 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-02-01 21:22:27 +00:00
import IPFS from 'ipfs'
import fileReaderPullStream from 'pull-file-reader'
2019-02-01 22:35:14 +00:00
import { Matcher } from '@areknawo/rex'
2019-02-02 19:56:08 +00:00
import { getImageType } from './images'
2019-02-01 21:22:27 +00:00
2019-02-01 22:35:14 +00:00
const ipfsMatcher = new Matcher().begin().find('/ipfs/')
2019-02-01 21:22:27 +00:00
const ipfs = new IPFS()
2019-02-01 22:35:14 +00:00
export const isIpfs = str => ipfsMatcher.test(str)
export const captureFile = (event, cb, imgCb) => {
2019-02-01 21:22:27 +00:00
event.stopPropagation()
event.preventDefault()
const file = event.target.files[0]
2019-02-01 22:35:14 +00:00
saveToIpfs(file, cb, imgCb)
2019-02-01 21:22:27 +00:00
}
2019-02-02 17:11:09 +00:00
const formatForIpfs = file => {
const { name, type } = file
const content = fileReaderPullStream(file)
return [{
path: `/root/${name}`,
content
}]
}
2019-02-01 22:35:14 +00:00
const saveToIpfs = (file, cb, imgCb) => {
2019-02-01 21:22:27 +00:00
let ipfsId
2019-02-02 17:11:09 +00:00
ipfs.add(formatForIpfs(file), { progress: (prog) => console.log(`received: ${prog}`) })
2019-02-01 21:22:27 +00:00
.then((response) => {
console.log(response)
ipfsId = response[0].hash
cb(`ipfs/${ipfsId}`)
2019-02-01 22:35:14 +00:00
getImageFromIpfs(ipfsId, imgCb)
2019-02-01 21:22:27 +00:00
}).catch((err) => {
console.error(err)
})
}
2019-02-01 22:35:14 +00:00
export const getImageFromIpfs = async (hash, cb) => {
2019-02-02 17:11:09 +00:00
const files = await getFile(hash)
const file = files.slice(-1)[0]
const { content } = file
const arrayBufferView = new Uint8Array(content)
2019-02-02 19:56:08 +00:00
const blob = new Blob([ arrayBufferView ], { type: getImageType(file) })
2019-02-02 17:11:09 +00:00
const img = URL.createObjectURL(blob)
cb({ ...file, img })
2019-02-01 22:35:14 +00:00
};
export const getFile = CID => {
return new Promise(function(resolve, reject) {
ipfs.get(CID, function (err, files) {
if (err) reject(err)
else resolve(files)
})
})
}