liquid-funding/app/utils/ipfs.js

73 lines
1.9 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
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-13 16:28:26 +00:00
const files = event.target.files
const formattedFiles = formatFileList(files)
console.log({files, formattedFiles})
saveToIpfs(formattedFiles, cb, imgCb)
}
const formatFileList = files => {
const formattedList = []
for (let i=0; i<files.length; i++) {
formattedList.push(formatForIpfs(files[i]))
}
return formattedList
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)
2019-02-13 16:28:26 +00:00
return {
2019-02-02 17:11:09 +00:00
path: `/root/${name}`,
content
2019-02-13 16:28:26 +00:00
}
2019-02-02 17:11:09 +00:00
}
2019-02-13 16:28:26 +00:00
const saveToIpfs = (files, cb, imgCb) => {
2019-02-01 21:22:27 +00:00
let ipfsId
2019-02-13 16:28:26 +00:00
ipfs.add(files, { 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) => {
const res = await getFromIpfs(hash)
cb(res)
};
export const getFromIpfs = async hash => {
2019-02-13 16:28:26 +00:00
const files = await getFiles(hash)
2019-02-02 17:11:09 +00:00
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)
return { ...file, img }
}
2019-02-01 22:35:14 +00:00
2019-02-13 16:28:26 +00:00
export const getFiles = CID => {
const clean = CID.split('/').slice(-1)[0]
2019-02-01 22:35:14 +00:00
return new Promise(function(resolve, reject) {
ipfs.get(clean, function (err, files) {
2019-02-01 22:35:14 +00:00
if (err) reject(err)
else resolve(files)
})
})
}