49 lines
1.3 KiB
JavaScript
Raw Normal View History

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